<?php
/**
 * Created by PhpStorm.
 * User: dale
 * Date: 2017/8/22
 * Time: 下午12:32
 */

namespace Bpm\Controllers;

use Admin\Models\bpm\XHBpmNode;
use Admin\Models\bpm\XHBpmPlan;
use Admin\Models\bpm\XHBpmChargerLog;
use Admin\Models\bpm\XHBpmPlanContent;
use Admin\Models\bpm\XHBpmTemplate;
use Admin\Models\bpm\XHBpmTransList;
use Admin\Models\crm\XhcustAuth;
use Admin\Models\hrm\XhhrmDepart;
use Admin\Models\hrm\XhhrmStaff;
use Admin\Models\ims\XHImsApplyTablet;
use Admin\Models\ims\XHImsBoxOut;
use Admin\Models\ims\XHImsProduce;
use Admin\Models\ims\XHImsProduceOut;
use Admin\Models\ims\XHImsReturnTab;
use Admin\Models\school\XhschoolInfo;
use Admin\Models\school\XhProjectHistory;
use Admin\Models\user\XhsysUser;
use Admin\Models\crm\XhcustInfo;
use Helpers\Assets;
use Helpers\Hrm;
use Helpers\HttpClient;
use Helpers\Main;
use Helpers\Queue;
use Helpers\Template;
use Admin\Models\sys\XhsysEnum;
use Helpers\Tool;
use Helpers\User;
use Helpers\UserPower;
use Helpers\XhException;
use Modules\Ims;
use Modules\Power;
use Modules\School;
use function PHPSTORM_META\map;

class PlanController extends ControllerBase
{


    public function notFoundAction()
    {
        return $this->response->setStatusCode(404)->setJsonContent(['code' => 404, 'error' => 'page not found!']);
    }

    public function runPlanIntoProjectHistoryAction()
    {
        $plans = XHBpmPlan::find([
            'conditions'=>'bDelete=0',
        ]);
        foreach ($plans as $plan) {
            $schoolId = XhcustInfo::findFirst($plan->iCUId)->iSchoolId; //学校id
            $data['iPlanId'] = $plan->iBPPId;//流程计划id
            $data['iSchoolId'] = $schoolId;
            $data['iState'] = !empty($plan->bFinish) ? $plan->bFinish : 2;//流程计划状态   1.已完成  2.进行中
            $applyInfo = $this->getTransInfo($plan->iBPPId);
            $data['sClass'] = $applyInfo['realClass'];//班级 逗号分割的字符串
            $data['iTeacher'] = $applyInfo['realTchNum'];//教师数
            $data['iStudent'] = $applyInfo['realStuNum'];//学生数
            $obj = XHBpmTransList::findFirst([
                'conditions'=>'bDelete=0 AND iBPPId=:iBPPId: ',
                'bind'=>array('iBPPId'=>$plan->iBPPId),
            ]);
            if (!empty($obj) && !empty($obj->tRunItemDate)) {
                    $data['tTime'] = $obj->tRunItemDate;
            }
            if (empty($data['tTime'])){
                $content = XHBpmPlanContent::findFirst([
                    'conditions'=>'bDelete=0 AND iBPPId =:id: And sNodeName  = "上线时间"',
                    'bind'=>array('id'=>$plan->iBPPId)
                ]);
                if (!empty($content) && !empty($content->tRealDate)) {
                    $data['tTime'] = $content->tRealDate;
                }
            }
            if (empty($data['tTime'])){
                $data['tTime'] = $plan->tLastModifyDate;
            }
            $data['sCooperate'] = '';
            if (!empty($obj)) {
                $iChargeMode= array_filter(explode(',',$obj->iChargeMode));
                $iChargeMode=  implode(',',$iChargeMode);
                $data['sCooperate'] = $iChargeMode;//合作方式
            }
            XhProjectHistory::insterData($data);
        }
    }
    
    /**
     * 计划列表
     *
     * created by dale 2017/8/22
     */
    public function planListAction(){
        $iCUId=$this->request->getQuery('iCUId');
        $iBPPId=$this->request->getQuery('iBPPId');
        $finish=$this->request->getQuery('finish');
        if($finish==1){
            if(!UserPower::checkUserPower('Bpm_PlanFinish')){
                return $this->sendViewError('缺少权限');
            }
        }else{
            if(!UserPower::checkUserPower('Bpm_Plan')){
                return $this->sendViewError('缺少权限');
            }
        }
        Main::showNavPosition();
        Assets::easyUI();
        Assets::importJs('js/myMain.js');
        $this->view->pick('plan/planList');
        Assets::importJs('js/plan/planList.js');
        Assets::importMainJs('assets/xh/xhForm.js');
        $this->di->get('assets')->addCss('bpm/css/Color.css');
        $iTPId=XHBpmTemplate::findFirst([
            'columns'=>'iTPId',
            'conditions'=>'bDelete=0',
        ]);
        $iTPId=$iTPId->iTPId;
        $arrs=XHBpmNode::find([
            'columns'=>'iNodeId,sNodeName',
            'conditions'=>'bDelete=0 AND iTPId=:iTPId:',
            'bind'=>['iTPId'=>$iTPId],
            'order'=>'iSort',
        ]);
        $arrs=array_column($arrs->toArray(),'sNodeName','sNodeName');
        $exDeps=XhhrmDepart::find([
            'columns'=>'iDepId,sDepName',
            'conditions'=>'bDelete=0 AND iParentId=0',
        ]);
        $exDeps=$exDeps->toArray();
        if (!UserPower::checkUserPower('Bpm_Plan_Edit')){
            $hideStatecss='#bt_list_state{
                            display: none; 
                        }';
        }else{
            $hideStatecss='';
        }

        $provinces = \Admin\Models\overt\XhovertAreainfo::getChildArea();
        $this->view->setVars([
            'iBPPId'=>$iBPPId,
            'iCUId'=>$iCUId,
            'nodes'=>$arrs,
            'finish'=>$finish,
            'provinces'=>$provinces,
            'exDeps'=>$exDeps,
            'planDel'=>UserPower::checkUserPower('Bpm_Plan_Del'),
            'planEdit'=>UserPower::checkUserPower('Bpm_Plan_Edit'),
            'hideStatecss'=>$hideStatecss,
            'planConfirm' => UserPower::checkUserPower('Bpm_Plan_Confirm'),
            'alterCharger' => UserPower::checkUserPower('Bpm_Plan_AlterHeadCharger'),
            'planState' => UserPower::checkUserPower('Bpm_Plan_Finance'),
            'finishPower' => UserPower::checkUserPower('Bpm_Plan_Finish'),
            'applyTab'    => Power::exist('Device_ApplyTab_Add'),
            'userId'      => Main::getLoginUserInfo('userId')
        ]);
    }



    public function getCityAction(){
        $areaCode= $this->request->getQuery('areaCode','string') ;
        if(!$areaCode){
            return $this->sendErrorResponse(400,'缺少参数');
        }
        $city=\Admin\Models\overt\XhovertAreainfo::getChildArea($areaCode);
        return $this->sendJsonResponse($city);
    }

    /**
     * 最近3个月内一条计划信息
     * @return string
     * created by dale 2017/8/26
     */
    public function beforeCreatePlanAction(){
        $iCUId=$this->request->getPost('iCUId','string');
        $obj=XHBpmPlan::findFirst([
            'conditions'=>'bDelete=0 AND iCUId =:id:',
            'bind'=>array('id'=>$iCUId),
            'order'=>'tCreateDate Desc'
        ]);
        if($obj){
            if(strtotime($obj->tCreateDate)<=(time()-86400*30*3)){
                return json_encode(['message'=>'error']);
            }else{
                $data=$obj->toArray();
                if($obj->mDesc==null){
                    $data['mDesc']='无';
                }
                $info=XhsysUser::getUserNameById([$data['iCreateUserId']]);
                $data['sCreateUserName']=$info[$data['iCreateUserId']];
                return $this->sendJsonResponse(['message'=>'success','data'=>$data]);
            }
        }else{
            return json_encode(['message'=>'error']);
        }

    }

    /**
     * 只读列表
     *
     * created by dale 2017/8/24
     */
    public function planReadListAction(){
//        $iCUId=$this->request->getQuery('iCUId');
        $iBPPId=$this->request->getQuery('iBPPId');
        Assets::easyUI();
        Assets::importJs('js/myMain.js');
        $this->view->pick('plan/panReadList');
        $this->di->get('assets')->addCss('bpm/css/Color.css');
        Assets::importJs('js/plan/planReadList.js');
        Assets::importMainJs('assets/xh/xhForm.js');
        $this->view->setVars([
            'iBPPId'=>$iBPPId,
        ]);
    }


    /**
     * content表单
     * created by dale 2017/8/22
     * modify by ck 20170922    更改财务对接权限判断
     * modify by dale 2018/3/2  关联客户信息
     */
    public function transFormAction(){
        $iBPPId=$this->request->getQuery('iBPPId','string');
        $type=$this->request->getQuery('type','string');
        $iChargeMode = XhsysEnum::getEnumByNodeName('收费模式');
        if($type==1){
            $plan=XHBpmPlan::findFirst($iBPPId);
            if(!Main::getLoginUserInfo('userId')&&$plan->tRealDate!=null){
                return $this->response->redirect('Index/login');
            }
            $this->di->get('assets')->addCss('bpm/css/Color.css');
            $this->view->pick('plan/readTrans');
            Assets::easyUI();
        }else{
            $this->view->pick('plan/transFrom');
        }
        Assets::select2();
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importJs('js/myMain.js');
        Assets::datetimePicker();
        Assets::importJs('js/plan/transForm.js');
        $obj = XHBpmTransList::findFirst([
            'conditions'=>'bDelete=0 AND iBPPId=:iBPPId: ',
            'bind'=>array('iBPPId'=>$iBPPId),
        ]);
        if ($obj) {
            $this->view->setVar('transInfo', $obj->toArray());
        }
        //根据 iBBPId获取custInfo
        $builder = $this->modelsManager->createBuilder()
                    ->columns('p.iBPPId,p.iCUId,c.sProvinceName,c.sCityName,c.sCountyName,
                    c.iMarketId,c.iOperateId,c.sDetailedAddress')
                    ->from(['p' => 'Admin\\Models\\bpm\\XHBpmPlan'])
                    ->leftJoin('Admin\\Models\\crm\\XhcustInfo','p.iCUId = c.iCUId','c')
                    ->where('p.bDelete = 0 and p.iBPPId = :iBPPId:', ['iBPPId' => $iBPPId ]);
        $cusInfo = $builder->getQuery()->execute()->toArray();
        $cusInfo = isset($cusInfo[0]) ? $cusInfo[0] : [];
//        $this->tag->setTitle($obj->sSchoolName);
        //var_dump($obj->toArray());die();
        $arrs=[
            'iChargeModes'=>$iChargeMode,
        ];
        if($obj){
            $data=$obj->toArray();

            // cusInfo 数据处理
            $data['province'] = $cusInfo['sProvinceName'];
            $data['city'] = $cusInfo['sCityName'];
            $data['country'] = $cusInfo['sCountyName'];
            $data['sSchoolAddress'] = isset($data['sSchoolAddress']) && $data['sSchoolAddress'] != '' ? $data['sSchoolAddress'] : $cusInfo['sDetailedAddress'];
            $data['iOperateId'] = $data['iOperateId'] ?: $cusInfo['iOperateId'];
            $data['iMarketId'] = $data['iMarketId']   ?: $cusInfo['iMarketId'];

            $data['sGrade']=explode(',',$data['sGrade']);
            $data['tabletVersion']=explode(',',$data['tabletVersion']);
            $data['sContentDate']=explode(',',$data['sContentDate']);
            $data['sPayDate']=explode(',',$data['sPayDate']);
            $data['iChargeMode']=explode(',',$data['iChargeMode']);
            $data['iTabletCost']=explode(',',$data['iTabletCost']);
            $data['iServiceCost']=explode(',',$data['iServiceCost']);
            $data['tPayedDate']=explode(',',$data['tPayedDate']);
            if($type == 1){
                $data['bKnow']   = $data['bKnow']   ? '知情' : '不知情';
                $data['bVerify'] = $data['bVerify'] ?  '是'  : '否';
                if($data['iMarketId']){
                    $data['iMarketId'] = XhsysUser::getUserNameById([$data['iMarketId']])[$data['iMarketId']] ;
                }
                if($data['iOperateId']){
                    $data['iOperateId'] = XhsysUser::getUserNameById([$data['iOperateId']])[$data['iOperateId']];
                }
            }

            $arrs['transData'] = json_encode($data);
        }else{
            $arrs['extra']['province']       = $cusInfo['sProvinceName'];
            $arrs['extra']['city']           = $cusInfo['sCityName'];
            $arrs['extra']['country']        = $cusInfo['sCountyName'];
            $arrs['extra']['sSchoolAddress'] = $cusInfo['sDetailedAddress'];
            $arrs['extra']['iOperateId']     =  $cusInfo['iOperateId'];
            $arrs['extra']['iMarketId']      =   $cusInfo['iMarketId'];
            $arrs['transData']      = '1';
        }
        $baseUrl=$this->di->getShared('url')->getBaseUri();
        if($obj){
            $arrs['readUrl']=$_SERVER['HTTP_HOST'].$baseUrl.'bpm/plan/transForm?type=1&iBPPId='.$iBPPId;
            $arrs['iBPPId']=$iBPPId;
        }else{
            $arrs['readUrl']='未创建,请先创建流转单';
        }
        $check=false;
        if(!$obj){//检查权限,第一次展开
            $check=true;
        }else{
            if (UserPower::checkUserPower('Bpm_Plan_Finance')) {
                $check=true;
            }
        }
        if ($iBPPId) {
            $applyTabArr = XHImsApplyTablet::find([
                'conditions' => 'bDelete = 0 and iBPPId = :iBPPId:',
                'bind'       => ['iBPPId' => $iBPPId],
            ])->toArray();
            $retTabArr = XHImsReturnTab::find([
                'conditions' => 'bDelete = 0 and iBPPId = :iBPPId:',
                'bind'       => ['iBPPId' => $iBPPId],
            ])->toArray();
            $applyInfo = [
                'realClass' => '',
                'realClassNum' => 0,
                'realTchNum' => 0,
                'realStuNum' => 0
            ];
            if ($applyTabArr) {
                $classArr = [];
                foreach ($applyTabArr as $applyTab) {
                    if ($applyTab['iState'] != 3) {
                        continue;
                    }
                    if ($applyTab['iType'] == 1) {
                        $applyInfo['realStuNum'] += Tool::getValue($applyTab, 'iStuNum', 0);
                        $applyInfo['realTchNum'] += Tool::getValue($applyTab, 'iTchNum', 0);
                        $class = Tool::getValue($applyTab, 'sClasses', '');
                        if ($class) {
                            $class = explode(',', $class);
                            $classArr = array_merge($classArr, $class);
                        }
                    } elseif ($applyTab['iType'] == 2) {
                        $applyInfo['realStuNum'] += Tool::getValue($applyTab, 'iStuNum', 0);
                        $classSql = "select sAdClsName from XHSys_User where iUserId in ({$applyTab['sStudents']})
                                  group by sAdClsName ";
                        $class = $this->db->fetchAll($classSql);
                        if ($class) {
                            $class = array_column($class, 'sAdClsName');
                            if ($class) {
                                $classArr = array_merge($classArr, $class);
                            }
                        }
                    } elseif ($applyTab['iType'] == 3) {
                        $applyInfo['realTchNum'] += Tool::getValue($applyTab, 'iTchNum', 0);
                    }
                }
                $classArr = array_values(array_unique(array_filter($classArr)));
                $applyInfo['realClass'] = implode(',', $classArr);
                $applyInfo['realClassNum'] = count($classArr);
            }

            if ($retTabArr) {
                foreach ($retTabArr as $retTab) {
                    if ($retTab['iState'] != 3) {
                        continue;
                    }
                    if (!is_array($retTab['mData'])) {
                        $retTab['mData'] = $retTab['mData'] ? unserialize($retTab['mData']) : [];
                    }
                    if ($retTab['iSource'] == 1) { //设备申领
                        foreach ($retTab['mData'] as $row) {
                            $devType = Tool::getValue($row, 'iReceivePurpose', '');
                            if ($devType &&  $devType == '教师机') {
                                $applyInfo['realTchNum'] -= 1;
                            }
                        }
//                        $applyInfo['realStuNum'] += Tool::getValue($applyTab, 'iStuNum', 0);
//                        $applyInfo['realTchNum'] += Tool::getValue($applyTab, 'iTchNum', 0);
//                        $class = Tool::getValue($applyTab, 'sClasses', '');
//                        if ($class) {
//                            $class = explode(',', $class);
//                            $classArr = array_merge($classArr, $class);
//                        }
                    } elseif ($retTab['iSource'] == 2) { //学生列表
                        $applyInfo['realStuNum'] -= count($retTab['mData']);
                    } elseif ($retTab['iSource'] == 3) { //教师列表
                        $applyInfo['realTchNum'] -= count($retTab['mData']);
                    }
                }
            }
            $this->view->setVar('applyInfo', $applyInfo);
        }

        $arrs['check'] = $check;
        $arrs['iMarketIds']       = Hrm::getDepStaffByTag('xhscb');
        $arrs['iOperateIds']      = Hrm::getDepStaffByTag('xhyyb');
        $year = [];
        $year[] = intval(date('Y',time()))+1;
        for($i =1 ;$i<=5;$i++){
            $year[$year[0] -$i] =  $year[0] -$i;
        }
        $year[$year[0]] = $year[0];
        unset($year[0]);
        $arrs['sYear'] = $year;
        $this->view->setVars($arrs);
    }

    

    
    
    public function saveTransAction(){
//        UserPower::checkUserPower('Bpm_Plan_Edit') or die('缺少权限');
        $iBPLId=$this->request->getPost('iBPLId');
        $flag=false;
        if($iBPLId==null){
            $flag=true;
            $obj=new XHBpmTransList();

        }else{
            $obj=XHBpmTransList::findFirst($iBPLId);
        }
        $data=$this->request->getPost();
        $data['tApplyDate']=($data['tApplyDate']==""?null:$data['tApplyDate']);
        $data['tVerifyDate']=($data['tVerifyDate']==""?null:$data['tVerifyDate']);
        $data['tParentTrain']=($data['tParentTrain']==""?null:$data['tParentTrain']);
        $data['tStuTrain']=($data['tStuTrain']==""?null:$data['tStuTrain']);
        $data['tNetTestDate']=($data['tNetTestDate']==""?null:$data['tNetTestDate']);
        $data['tTechInTrain']=($data['tTechInTrain']==""?null:$data['tTechInTrain']);
        $data['tTechOpTrain']=($data['tTechOpTrain']==""?null:$data['tTechOpTrain']);
        $data['tRunItemDate']=($data['tRunItemDate']==""?null:$data['tRunItemDate']);



//        $data['iStudentNum']=($data['iStudentNum']==""?null:$data['iStudentNum']);;
//        $data['iTeacherNum']=($data['iTeacherNum']==""?null:$data['iTeacherNum']);
//        $data['iClassNum']=($data['iClassNum']==""?null:$data['iClassNum']);

        $data['iOfficeNum']=($data['iOfficeNum']==""?null:$data['iOfficeNum']);
        $data['iOtherNum']=($data['iOtherNum']==""?null:$data['iOtherNum']);
        $data['iTchRoom']=($data['iTchRoom']==""?null:$data['iTchRoom']);
        if(isset($data['sYear'])){
            $data['sYear'] = implode(',',$data['sYear']);
        }else{
            $data['sYear'] = null;
        }
        if(isset($data['sGrade'])){
            $data['sGrade']= implode(',',$data['sGrade']);
        }
        if(isset( $data['tabletVersion'])){
            $data['tabletVersion']=implode(',',$data['tabletVersion']);
        }
        if(isset($data['sContentDate'])){
            $data['sContentDate']=implode(',',$data['sContentDate']);
        }
        if(isset($data['sPayDate'])){
            $data['sPayDate']=implode(',',$data['sPayDate']);
        }
        if(isset($data['iChargeMode'])){
            $data['iChargeMode']=implode(',',$data['iChargeMode']);
        }
        if(isset($data['iTabletCost'])){
            $data['iTabletCost']=implode(',',$data['iTabletCost']);
        }
        if(isset($data['iServiceCost'])){
            $data['iServiceCost']=implode(',',$data['iServiceCost']);
        }
        if(isset($data['tPayedDate'])){
            $data['tPayedDate']=implode(',',$data['tPayedDate']);
        }
        $obj->assign($data);
        if(!$obj->save()){
            return $this->sendErrorResponse(500,'失败');
        }
        if($flag){
            $sendTest=$this->sendMsgToPhoneAction($this->request->getPost('sSchoolName'),$flag);
            $this->praseLog('发送信息失败，电话'.$sendTest['errPhones'].'，成功电话：'.$sendTest['successPhones'],
                '发送信息失败，电话'.$sendTest['errPhones'].'，成功电话：'.$sendTest['successPhones']);
        }
        return $this->sendSuccessResponse('成功');
    }

    public function sendMsgToPhoneAction($sSchoolName,$flag){
        if(!$flag){
            return false;
        }
        $config=Main::getConfigByName('bpm');
        $msg=$sSchoolName.'流转单已开启';
        $phoneArr = array_filter(explode(',',$config['transPhone']));
        $errPhones = [];
        $successPhones = [];
        foreach ($phoneArr as $value){
            $value = trim($value);
            if(!$this->sendMsgToPhone($value,$msg)){
                $errPhones[] = $value;
            }else{
                $successPhones[] =  $value;
            }
        }
        return ['errPhones'=>implode(',',$errPhones),'successPhones'=>implode(',',$successPhones)];
    }

    public function sendMsgToPhone($phoneNum, $msg){
        return Main::sendSMS($phoneNum, $msg);
//        $data = [
//            'appId'	=> 'platform',
//            'clientId'	=> $phoneNum,
//            'payload'	=> $msg,
//            'type'		=> 'SMS'
//        ];
//        $http = new HttpClient();
//        $url  = Main::getConfigByName('bpm')['msgUrl'];
//        $response = $http->postJson($url, $data);
//        if(!$response->isSuccess()) return false;
//        $body = $response->toArray();
//        return $body['code'] == 'OK' ? true : false;
    }


    /**
     * content表单
     * created by dale 2017/8/22
     */
    public function contentFormAction(){
        $id=$this->request->getQuery('id','string');
        if(UserPower::checkUserPower('Bpm_Plan_All')&&UserPower::checkUserPower('Bpm_Plan_Edit')){

        }else{
            $obj=XHBpmPlanContent::findFirst([
                'conditions'=>'bDelete=0 AND iBPCId =:id:',
                'bind'=>array('id'=>$id)
            ]);
            $check=XhhrmStaff::findFirst([
                'columns'=>'iStaffId,sStaffName,iUserId',
                'conditions'=>"bDelete=0 AND sDepIds like :id: AND iUserId=:iUserId:",
                'bind'=>array("id"=>'%,'.$obj->sExcuteDeps.',%','iUserId'=>Main::getLoginUserInfo('userId'))
            ]);
            if(!$check){
                $checkStr= "parent.$('#bt_modal_confirm').hide();";
            }else{
                $checkStr="";
            }
        }


        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::easyUI();
        Assets::importJs('js/myMain.js');
        Assets::datetimePicker();
        Assets::importJs('js/plan/contentForm.js');
        $this->view->pick('plan/contentForm');
        if($id){
            $obj=XHBpmPlanContent::findFirst([
                'conditions'=>'bDelete=0 AND iBPCId =:id:',
                'bind'=>array('id'=>$id)
            ]);
            $node=XHBpmNode::findFirst([
                'conditions'=>'bDelete=0 AND sNodeName=:sNodeName:',
                'bind'=>['sNodeName'=>$obj->sNodeName]
            ]);
            if($node){
                $desc=$node->mDesc;
                $desc=str_replace(array("\r\n", "\r", "\n"),'<br>',$desc);
            }else{
                $desc='';
            }



            $staffs=XhhrmStaff::find([
                'columns'=>'iStaffId,sStaffName,iUserId',
                'conditions'=>"bDelete=0 AND sDepIds like :id:",
                'bind'=>array("id"=>'%,'.$obj->sExcuteDeps.',%')
            ]);
            $pEnums=array_column($staffs->toArray(),'sStaffName','iUserId');

            $webArr = [
                'lock'=>$obj->bLock,
                'contentInfo'=>json_encode($obj->toArray()),
                'pEnums'=>$pEnums,
                'check'=>$checkStr,
                'desc'=>$desc,
            ];

            $outNums = XHImsProduceOut::find([
                'conditions' => 'bDelete = 0 AND iOutTypeId = :iOutTypeId: and iOutType = 3 ',
                'bind'       => ['iOutTypeId' => $id]
            ])->toArray();
            if(count($outNums) > 0){
                $webArr['outNums'] = json_encode($outNums);
            }

            $this->view->setVars($webArr);
        }
    }

    /**
     * 保存详情
     *
     * @return string
     * created by dale 2017/8/23
     */
    public function saveContentAction(){
//        UserPower::checkUserPower('Bpm_Plan_Edit')or die('缺少权限');
        $iBPCId=$this->request->getPost('iBPCId','string');
        if(!(UserPower::checkUserPower('Bpm_Plan_All') && UserPower::checkUserPower('Bpm_Plan_Edit'))){
            $obj=XHBpmPlanContent::findFirst([
                'conditions'=>'bDelete=0 AND iBPCId =:id:',
                'bind'=>array('id'=>$iBPCId)
            ]);
            $check=XhhrmStaff::findFirst([
                'columns'=>'iStaffId,sStaffName,iUserId',
                'conditions'=>"bDelete=0 AND sDepIds like :id: AND iUserId=:iUserId:",
                'bind'=>array("id"=>'%,'.$obj->sExcuteDeps.',%','iUserId'=>Main::getLoginUserInfo('userId'))
            ]);
            if(!$check){
                return $this->sendErrorResponse(400,'没有权限');
            }
        }
        try {
            $this->db->begin();
            if($iBPCId!=null){
                $obj=XHBpmPlanContent::findFirst([
                    'conditions'=>'bDelete=0 AND iBPCId =:id:',
                    'bind'=>array('id'=>$iBPCId)
                ]);
            }else{
                $obj=new XHBpmPlanContent();
            }
            $obj->assign($this->request->getPost());
            if($obj->tPlanDate==null){
                $obj->tPlanDate = ($this->request->getPost('tPlanDate')==""?null:$this->request->getPost('tPlanDate'));
            }
            $obj->tRealDate =  ($this->request->getPost('tRealDate')==""?null:$this->request->getPost('tRealDate'));
            if($obj->tRealDate!=null){
//            if($obj->tRealDate>date('Y-m-d',time())){
//                return '实际完成时间不得超过当前时间';
//            }else
                if($obj->tPlanDate==null){
                    return $this->sendErrorResponse(500,'预计完成时间还没确定');
                }else{
                    $obj->sExcProcess=100;
                }
            }
            if($this->request->getPost('iChargeId')){
                $obj->iChargeId =  ($this->request->getPost('iChargeId')==""?null:$this->request->getPost('iChargeId'));
            }
//        $obj->tLastModifyDate=date('Y-m-d H:i:s', time());
//        $obj->iLastModifyUserId=Main::getLoginUserInfo('userId');
            if($obj->save()){
                if($obj->tRealDate){
                    $checkReal=$this->checkRealTime($obj->iBPPId);
                }else{
                    $checkReal=false;
                }
                $plan=XHBpmPlan::findFirst([
                    'conditions'=>'bDelete=0 AND iBPPId=:iBPPId:',
                    'bind' =>array('iBPPId'=>$obj->iBPPId)
                ]);
                if(!$plan){
                    $this->db->rollback();
                    return $this->sendErrorResponse(500,'没有这个计划');
                }
                if($checkReal){
                    $plan->tRealDate = $this->getHeightTime($obj->iBPPId);
                    $plan->bFinish   = 1;
                }
                $plan->tLastModifyDate   = $obj->tLastModifyDate;
                $plan->iLastModifyUserId = $obj->iLastModifyUserId;
                if(!$plan->save()){
                    $this->db->rollback();
                    return $this->sendErrorResponse(500,'计划保存失败');
                }
                $schoolId = XhcustInfo::findFirst($plan->iCUId)->iSchoolId; //学校id
                if($obj->sExcProcess == 100 && $obj->tRealDate != null && $obj->sNodeName == '充电机箱确认' ) { //充电机箱
                    $data = $this->request->getPost('prodNum');
                    if(!$this->outPlan($data,$schoolId,$obj->iBPCId)){
                        $this->db->rollback();
                        return $this->sendErrorResponse(500,'出库保存失败');
                    }
                }

                    $data['tTime'] = $obj->tRealDate;
                    $data['iSchoolId'] = $schoolId;
                    $data['iPlanId'] = $obj->iBPPId;//流程计划id
                    $data['iState'] = !empty($plan->bFinish) ? $plan->bFinish : 2;//流程计划状态   1.已完成  2.进行中
                    $applyInfo = $this->getTransInfo($obj->iBPPId);
                    $data['sClass'] = $applyInfo['realClass'];//班级 逗号分割的字符串
                    $data['iTeacher'] = $applyInfo['realTchNum'];//教师数
                    $data['iStudent'] = $applyInfo['realStuNum'];//学生数
                    $tranObj = XHBpmTransList::findFirst([
                    'conditions'=>'bDelete=0 AND iBPPId=:iBPPId: ',
                    'bind'=>array('iBPPId'=>$plan->iBPPId),
                     ]);
                    $data['sCooperate']  = '';
                    if (!empty($tranObj)) {
                        $iChargeMode= array_filter(explode(',',$tranObj->iChargeMode));
                        $iChargeMode=  implode(',',$iChargeMode);
                        $data['sCooperate'] = $iChargeMode;//合作方式
                    }
                    $re = XhProjectHistory::insterData($data);
                    if (!$re) {
                        $this->db->rollback();
                        return $this->sendErrorResponse(500,'计划历史保存失败');
                    }

                $this->db->commit();
                return $this->sendSuccessResponse('保存成功');
            }else{
                $this->db->rollback();
                return $this->sendErrorResponse(500,'保存失败');
            }
        }
        catch (\Exception $exception) {
            return $this->sendErrorResponse(500,'保存失败',$exception->getMessage());
        }

    }

    private function getTransInfo($iBPPId) {

        $applyTabArr = XHImsApplyTablet::find([
            'conditions' => 'bDelete = 0 and iBPPId = :iBPPId:',
            'bind'       => ['iBPPId' => $iBPPId],
        ])->toArray();
        $retTabArr = XHImsReturnTab::find([
            'conditions' => 'bDelete = 0 and iBPPId = :iBPPId:',
            'bind'       => ['iBPPId' => $iBPPId],
        ])->toArray();
        $applyInfo = [
            'realClass' => '',
            'realClassNum' => 0,
            'realTchNum' => 0,
            'realStuNum' => 0
        ];
        if ($applyTabArr) {
            $classArr = [];
            foreach ($applyTabArr as $applyTab) {
                if ($applyTab['iState'] != 3) {
                    continue;
                }
                if ($applyTab['iType'] == 1) {
                    $applyInfo['realStuNum'] += Tool::getValue($applyTab, 'iStuNum', 0);
                    $applyInfo['realTchNum'] += Tool::getValue($applyTab, 'iTchNum', 0);
                    $class = Tool::getValue($applyTab, 'sClasses', '');
                    if ($class) {
                        $class = explode(',', $class);
                        $classArr = array_merge($classArr, $class);
                    }
                } elseif ($applyTab['iType'] == 2) {
                    $applyInfo['realStuNum'] += Tool::getValue($applyTab, 'iStuNum', 0);
                    $classSql = "select sAdClsName from XHSys_User where iUserId in ({$applyTab['sStudents']})
                                  group by sAdClsName ";
                    $class = $this->db->fetchAll($classSql);
                    if ($class) {
                        $class = array_column($class, 'sAdClsName');
                        if ($class) {
                            $classArr = array_merge($classArr, $class);
                        }
                    }
                } elseif ($applyTab['iType'] == 3) {
                    $applyInfo['realTchNum'] += Tool::getValue($applyTab, 'iTchNum', 0);
                }
            }
            $classArr = array_values(array_unique(array_filter($classArr)));
            $applyInfo['realClass'] = implode(',', $classArr);
            $applyInfo['realClassNum'] = count($classArr);
        }

        if ($retTabArr) {
            foreach ($retTabArr as $retTab) {
                if ($retTab['iState'] != 3) {
                    continue;
                }
                if (!is_array($retTab['mData'])) {
                    $retTab['mData'] = $retTab['mData'] ? unserialize($retTab['mData']) : [];
                }
                if ($retTab['iSource'] == 1) { //设备申领
                    foreach ($retTab['mData'] as $row) {
                        $devType = Tool::getValue($row, 'iReceivePurpose', '');
                        if ($devType &&  $devType == '教师机') {
                            $applyInfo['realTchNum'] -= 1;
                        }
                    }
                } elseif ($retTab['iSource'] == 2) { //学生列表
                    $applyInfo['realStuNum'] -= count($retTab['mData']);
                } elseif ($retTab['iSource'] == 3) { //教师列表
                    $applyInfo['realTchNum'] -= count($retTab['mData']);
                }
            }
        }
        return $applyInfo;
    }


    public function checkRealTime($iBPPId){
        $contents=XHBpmPlanContent::find([
            'conditions'=>'bDelete=0 AND iBPPId =:id:',
            'bind'=>array('id'=>$iBPPId)
        ]);
        foreach ($contents as $content){
            if($content->tRealDate==null){
                return false;
            }
        }
        return true;
    }

    public function getHeightTime($iBPPId){
        $contents=XHBpmPlanContent::find([
            'conditions'=>'bDelete=0 AND iBPPId =:id:',
            'bind'=>array('id'=>$iBPPId)
        ]);
        $max='1970-1-1';
        foreach ($contents as $content){
            if($content->tRealDate != null){
                if($max<=$content->tRealDate){
                    $max=$content->tRealDate;
                }
            }
        }
        return $max;
    }
    
    public function planFormAction(){
        //$id=$this->request->getQuery('id','string');
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::easyUI();
        Assets::importJs('js/myMain.js');
        Assets::datetimePicker();
        Assets::importJs('js/plan/planForm.js');
        $this->view->pick('plan/planForm');
        $obj=XHBpmTemplate::find([
            'columns'=>'iTPId,sTPName',
            'conditions'=>'bDelete=0',
        ]);
        $tenums=array_column($obj->toArray(),'sTPName','iTPId');
        $this->view->setVars([
            'tenums'=>$tenums,
        ]);
        
    }
    
    
    /**
     * 保存plan,并创建planContent
     * @return string
     * created by dale 2017/8/23 
     */
    public function savePlanAction(){
        try {
            $this->db->begin();
            if (!UserPower::checkUserPower('Bpm_Plan_Add')){
                return json_encode(['code' => 403, 'msg' => '缺少权限']);
            };
            $iBPPId=$this->request->getPost('iBPPId','string');
            $iTPId=$this->request->getPost('iTPId','string');
            $iCUId = $this->request->getPost('iCUId', 'int');
            if($iBPPId!=null){
                $obj=XHBpmPlan::findFirst([
                    'conditions'=>'bDelete=0 AND iBPPId =:id:',
                    'bind'=>array('id'=>$iBPPId)
                ]);
            }else{
                $obj=new XHBpmPlan();
            }
            if ($iCUId) {
                $cusInfo = XhcustInfo::findFirst($iCUId);
                if (!$cusInfo->iSchoolId) { //创建学校并关联
                    $school = new XhschoolInfo();
                    $school->sSchoolName = $cusInfo->sSchoolName;
                    $school->iStatus = 1;
                    $school->sProvinceName = $cusInfo->sProvinceName;
                    $school->sCityName =  $cusInfo->sCityName;
                    $school->sCountyName = $cusInfo->sCountyName;
                    $school->iStage  = $cusInfo->iStage;
                    $school->bWelfare = $cusInfo->bWelfare;
                    if (!$school->save()) {
                        $this->db->rollback();
                        return json_encode(['code' => 500, 'msg' => '学校保存失败']);
                    }
                    $cusInfo->iSchoolId = $school->iSchoolId;
                    if (!$cusInfo->save()){
                        $this->db->rollback();
                        return json_encode(['code' => 500, 'msg' => '学校id保存失败']);
                    }
                }
            }
            $obj->assign($this->request->getPost());
            $obj->iChargeId=Main::getLoginUserInfo('userId');
            if(!$obj->save()){
                return json_encode(['code'=>'500', '保存失败']);
            }
            $nodes=XHBpmNode::find([
                'columns'=>'iNodeId,sNodeName,sExcuteDeps,sExcuteIds,sRelatDeps,sRelatIds,iSort',
                'conditions'=>'bDelete=0 AND iTPId =:id:',
                'bind'=>array('id'=>$iTPId)
            ]);
            $UserId=Main::getLoginUserInfo('userId');
            foreach ($nodes as $node) {
                $pc=new XHBpmPlanContent();
                $pc->iBPPId      = $obj->iBPPId;
                $pc->sNodeName   = $node->sNodeName;
                $pc->sExcuteDeps = $node->sExcuteDeps;
                $pc->sExcuteIds  = $node->sExcuteIds;
                $pc->sRelatDeps  = $node->sRelatDeps;
                $pc->sRelatIds   = $node->sRelatIds;
                $pc->iSort       = $node->iSort;
                $check=XhhrmStaff::findFirst([
                    'conditions'=>"bDelete=0 AND sDepIds like :id: AND iUserId=:iUserId:",
                    'bind'=>array("id"=>'%,'.$node->sExcuteDeps.',%','iUserId'=>$UserId),
                ]);
                if($check){
                    $pc->iChargeId=$UserId;
                }
                if(!$pc->save()) {
                    $this->db->rollback();
                   return json_encode(['code'=>'500', '子节点保存失败']);
                }
            }
            $this->db->commit();
            return json_encode(['code'=> 200,'message'=>'success','iBPPId'=>$obj->iBPPId]);
        } catch (\Exception $e) {
            $this->db->rollback();
            return json_encode(['code' => 500, 'msg' => $e->getMessage()]);
        }
    }


    public function uploadContentAction(){
        $this->view->disable();
        $iNodeId=$this->request->getPost('iNodeId','string') or die('缺少参数');
        $node=XHBpmNode::findFirst([
            'conditions'=>'bDelete=0 AND iNodeId=:iNodeId:',
            'bind' =>['iNodeId'=>$iNodeId]
        ]);

        if($node){
            $plans=XHBpmPlan::find([
                'columns'=>'iBPPId',
                'conditions'=>'bDelete=0 AND iTPId=:iTPId:',
                'bind' =>['iTPId'=>$node->iTPId]
            ]);
            $plans=$plans->toArray();
            if($plans==[]){
                return json_encode(['message'=>'错误找不到要更新的计划']);
            }
            $UserId=Main::getLoginUserInfo('userId');
            foreach ($plans as $index=>$row){
                $pc=XHBpmPlanContent::findFirst([
                    'conditions'=>'bDelete=0 AND sNodeName=:sNodeName: AND iBPPId=:iBPPId:',
                    'bind' =>['sNodeName'=>$node->sNodeName,'iBPPId'=>$row['iBPPId']]
                ]) or $pc=new XHBpmPlanContent();
                $pc->iBPPId      = $row['iBPPId'];
                $pc->sNodeName   = $node->sNodeName;
                $pc->sExcuteDeps = $node->sExcuteDeps;
                $pc->sExcuteIds  = $node->sExcuteIds;
                $pc->sRelatDeps  = $node->sRelatDeps;
                $pc->sRelatIds   = $node->sRelatIds;
                $pc->iSort       = $node->iSort;
                $check=XhhrmStaff::findFirst([
                    'conditions'=>"bDelete=0 AND sDepIds like :id: AND iUserId=:iUserId:",
                    'bind'=>array("id"=>'%,'.$node->sExcuteDeps.',%','iUserId'=>$UserId),
                ]);
                if($check){
                    if($pc->iChargeId==null){
                        $pc->iChargeId=$UserId;
                    }
                }
                if(!$pc->save()) {
                    return json_encode(['message'=>'错误,保存出错']);
                }
            }

            return json_encode(['message'=>'success']);

        }else{
            return json_encode(['message'=>'错误,找不到node']);
        }

    }


    /**
     * 获取计划表数据
     * 
     * created by dale 2017/8/22
     * modify by ck 20170922    添加是否确认状态
     */
    public function getPlanAction(){
        try{
            if($this->request->getQuery('ctype')!=2){
                UserPower::checkUserPower('Bpm_Plan') or die('权限不足');
            }
            $openId = $this->request->getPost('openId','string');
            $type   = $this->request->getPost('type','string'); //所属类型
            $startTime = $this->request->getPost('startTime','string') ;
            $endTime  = $this->request->getPost('endTime','string')  ;
            $sNodeName = $this->request->getPost('sNodeName','string') ;
            $iBPPId = $this->request->getQuery('iBPPId','string');
            $iCUId = $this->request->getQuery('iCUId','string');
            $tsort = $this->request->getPost('tsort','string');
            $key = $this->request->getPost('key','string');
            $province = $this->request->getPost('province','string');
            $citys = $this->request->getPost('city','string');
            $sort = $this->request->getPost('sort','string');
            $order = $this->request->getPost('order','string');
            $iState = $this->request->getPost('iState','string');
            $finish =$this->request->getQuery('finish','string');
            $all = $this->request->getPost('all','string');
            $receiveType = $this->request->getPost('receiveType', 'string');

            if($citys!=null){
                $citys= array_values(array_filter(explode(',',$citys)));
            }else{
                $citys=[];
            }
            $builder = $this->modelsManager->createBuilder()
                ->columns('p.iBPPId,p.iCUId,p.tStartTime,p.iChargeId,p.tPlanDate,p.tRealDate,p.mDesc,p.tCreateDate,p.bApplyTab,p.iState,p.iCreateUserId,p.tLastModifyDate,p.iLastModifyUserId,i.iSchoolId,i.sSchoolName,i.sProvinceName,i.sCityName,s.sStaffName as sChargeName,s.sSelfPhone,i.iCreateUserId as customerCreator')
                ->addFrom('Admin\Models\bpm\XHBpmPlan', 'p')
                ->leftJoin('Admin\Models\crm\XhcustInfo', 'i.iCUId=p.iCUId', 'i')
                ->leftJoin('Admin\Models\hrm\XhhrmStaff','p.iChargeId=s.iUserId','s')
                ->where('p.bDelete=0');

            $builder->andWhere('p.bFinish=:bFinish:', ['bFinish' => $finish ? 1 : 0]);

            $depEnum=XhhrmDepart::getDepEnum();

            if($iState){
                $builder->andWhere('p.iState=:iState:',array('iState'=>$iState));
            }
            if ($receiveType) {
                $applyTabArr = XHImsApplyTablet::find([
                    'columns' => 'iRTId, iBPPId,iState,iType',
                    'conditions' => 'bDelete = 0 and iBPPId is not null',
                ])->toArray();
                if ($receiveType == 3) {
                    $builder->andWhere('iBPPId not in ({filterApply:array})',
                        ['filterApply' => array_values(array_filter(array_unique(array_column($applyTabArr, 'iBPPId'))))]);
                } else if ($receiveType == 1 || $receiveType == 2) {
                    if ($applyTabArr) {
                        $unAppIdArr = [];
                        foreach ($applyTabArr as $applyTab) {
                            if ($applyTab['iState'] != 3) {
                                $unAppIdArr[] = $applyTab['iBPPId'];
                            }
                        }
                        $unAppIdArr = array_values(array_filter(array_unique($unAppIdArr)));
                        if ($receiveType == 1) {
                            if ($unAppIdArr) {
                                $builder->andWhere('iBPPId in ({filterApply:array})', ['filterApply' => $unAppIdArr]);
                            } else {
                                return $this->sendJsonResponse(['rows' => [],'total' => 0]);
                            }
                        }
                        if ($receiveType == 2) {
                            $appIdArr = array_values(array_filter(array_unique(array_column($applyTabArr, 'iBPPId'))));
                            foreach ($appIdArr as $index => $appId) {
                                if (in_array($appId, $unAppIdArr)) {
                                    unset($appIdArr[$index]);
                                }
                            }
                            $appIdArr = array_values($appIdArr);
                            if ($appIdArr) {
                                $builder->andWhere('iBPPId in ({filterApply:array})', ['filterApply' => $appIdArr]);
                            } else {
                                return $this->sendJsonResponse(['rows' => [],'total' => 0]);
                            }
                        }

                    }
                }


            }
            if($province&&$province!='全部省'){
                $builder->andWhere('i.sProvinceName=:province:',array('province'=>$province));
            }
            if($citys!=[]&&$citys[0]!='全部市'){
                $builder->andWhere('i.sCityName in ({names:array})',array('names'=>$citys));
            }

            if($iBPPId!=null&&$iCUId==null&&$openId==null){
                $openId=$iBPPId;
                $builder->andWhere('p.iBPPId=:iBPPId:',array('iBPPId'=>$iBPPId));
            }else if($iBPPId!=null&&$iCUId!=null&&$openId==null){
                $openId=$iBPPId;
                $builder->andWhere('p.iCUId=:iCUId:',array('iCUId'=>$iCUId));
            }

            if($sNodeName){
                $builder->leftJoin('Admin\Models\bpm\XHBpmPlanContent','p.iBPPId=c.iBPPId ','c')->columns('p.iBPPId,p.iCUId,p.tStartTime,p.iState,p.iChargeId,p.tPlanDate,p.tRealDate,p.mDesc,p.tCreateDate,p.iCreateUserId,p.tLastModifyDate,p.iLastModifyUserId,i.sSchoolName,i.sProvinceName,i.sCityName,c.tPlanDate as cPlanDate ,c.iType as cType ,c.iBPCId,s.sSelfPhone,s.sStaffName as sChargeName')
                    ->andWhere('c.sNodeName=:sNodeName:',array('sNodeName'=>$sNodeName));
                //权限处理部分
                $schools = School::getPower();//获取学校权限
                if (!User::isAdmin() && $schools !== true) {
                    $conditionArr = [
                        'conditions' => [],
                        'bind'       => []
                    ];
                    if (count($schools) > 0) {
                        $conditionArr['conditions'][] = 'i.iSchoolId in ({schools:array})';
                        $conditionArr['bind']  = ['schools' => $schools];
//                            $builder->andWhere('', ['schools' => $schools]);
                    }
                    $auth = XhcustAuth::find([
                        'columns'    => 'iCUId',
                        'conditions' => 'bDelete=0 AND iAuthId=:iAuthId:',
                        'bind' => array('iAuthId' => Main::getLoginUserInfo('userId'))
                    ])->toArray();
                    if (count($auth) > 0) {
                        $authCuIds = array_values(array_filter(array_unique(array_column($auth, 'iCUId'))));
                        if ($authCuIds) {
                            $conditionArr['conditions'][] = 'p.iCUId in ({authCUIds:array})';
                            $conditionArr['bind']  = array_merge(['authCUIds' => $authCuIds], $conditionArr['bind']);
                        }
                    }
                    $conditionArr['conditions'][] = 'i.iCreateUserId = :nowId: ';
                    $conditionArr['bind']  =  array_merge(['nowId' => Main::getLoginUserInfo('userId')], $conditionArr['bind']);
                    $depArr = User::getExtraPower('dep', 'customer'); //获取客户的部门权限
                    if ($depArr) {
                        $userIds = array_values(array_filter(Hrm::getUserByDepId($depArr , true)));
                        if (count($userIds) > 0) {
                            $conditionArr['conditions'][] = 'i.iCreateUserId in ({users:array}) ';
                            $conditionArr['bind']  =  array_merge(['users' => $userIds], $conditionArr['bind']);
                        }
                    }
                    $conditionArr['conditions'][] = ' p.iChargeId=:iChargeId: OR c.iChargeId=:iChargeId: OR c.sExcuteIds=:iChargeId: ';
                    $conditionArr['bind']  =  array_merge(['iChargeId' => Main::getLoginUserInfo('userId')], $conditionArr['bind']);
                    $builder->andWhere(implode(' or ', $conditionArr['conditions']), $conditionArr['bind']);
                }


//            $userId=Main::getLoginUserInfo('userId');
//            if(!UserPower::checkUserPower('Bpm_Plan_All')){
//                $builder->andWhere('p.iChargeId=:iChargeId: OR c.iChargeId=:iChargeId: OR c.sExcuteIds=:iChargeId:',array('iChargeId'=>$userId));
//            }

                if($startTime==null&&$endTime){
                    $startTime='1970-01-01';
                }
                if($endTime==null&&$startTime){
                    $endTime=date('Y-m-d',time());
                }
                if($startTime&&$endTime){
                    $builder->andWhere('c.tPlanDate>=:startTime:',array('startTime'=>$startTime))->andWhere('c.tPlanDate<=:endTime:',array('endTime'=>$endTime));

                }
                if($type){
//                $builder->andWhere('c.iType=:iType:',array('iType'=>$type));
                    if($type==8){
                        $builder->andWhere('c.iType in ({types:array})',array('types'=>[5,6,7]));
                    }else{
                        $builder->andWhere('c.iType=:iType:',array('iType'=>$type));
                    }

                }
                if($tsort==2){
                    if($sort&&$order){
                        if($sort=="name"){
                            $sort='sSchoolName';
                            $builder->orderBy('c.tPlanDate DESC'.', i.'.$sort.' '.$order.'');
                        }else{
                            $builder->orderBy('c.tPlanDate DESC'.', p.'.$sort.' '.$order.'');
                        }
                    }else{
                        $builder->orderBy('c.tPlanDate DESC');
                    }

                }else if($tsort==1){
                    if($sort&&$order){
                        if($sort=="name"){
                            $sort='sSchoolName';
                            $builder->orderBy('c.tPlanDate '.', i.'.$sort.' '.$order.'');
                        }else{
                            $builder->orderBy('c.tPlanDate '.', p.'.$sort.' '.$order.'');
                        }
                    }else{
                        $builder->orderBy('c.tPlanDate ');
                    }
                }else{
                    if($sort&&$order) {
                        if ($sort == "name") {
                            $sort = 'sSchoolName';
                            $builder->orderBy(' i.' . $sort . ' ' . $order . '');
                        } else {
                            $builder->orderBy(' p.' . $sort . ' ' . $order . '');
                        }
                    }else{
                        $builder->orderBy('p.tCreateDate desc');
                    }
                }

            }else{
                $newBuilder=$this->modelsManager->createBuilder()
                    ->columns('p.iBPPId,p.iCUId,p.tStartTime,p.iChargeId,p.tPlanDate,p.tRealDate,p.mDesc,p.tCreateDate,p.iCreateUserId,p.tLastModifyDate,p.iLastModifyUserId,i.iSchoolId,,i.sSchoolName,i.sProvinceName,i.sCityName,s.sSelfPhone,i.iCreateUserId as customerCreator')
                    ->addFrom('Admin\Models\bpm\XHBpmPlan', 'p')
                    ->leftJoin('Admin\Models\crm\XhcustInfo', 'i.iCUId=p.iCUId', 'i')
                    ->leftJoin('Admin\Models\hrm\XhhrmStaff','p.iChargeId=s.iUserId','s')
                    ->where('p.bDelete=0');

                if($finish){
                    $newBuilder->andWhere('p.bFinish=:bFinish:',array('bFinish'=>1));
                }else{
                    $newBuilder->andWhere('p.bFinish=:bFinish:',array('bFinish'=>0));
                }


                if($province&&$province!='全部省'){
                    $newBuilder->andWhere('i.sProvinceName=:province:',array('province'=>$province));
                }
                if($citys!=[]&&$citys[0]!='全部市'){
                    $builder->andWhere('i.sCityName in ({names:array})',array('names'=>$citys));
                }
                $newBuilder->leftJoin('Admin\Models\bpm\XHBpmPlanContent','p.iBPPId=c.iBPPId ','c')->columns('p.iBPPId,c.iBPCId,c.sNodeName,c.tPlanDate as cPlanDate');
                if($startTime==null&&$endTime){
                    $startTime='1970-01-01';
                }
//                $startTime = $startTime ?: '1970-01-01';
                if($endTime==null&&$startTime){
                    $endTime=date('Y-m-d',time());
                }
//                $endTime = $endTime ?: date('Y-m-d',time());
                if($startTime&&$endTime){
                    $newBuilder->andWhere('c.tPlanDate>=:startTime:',array('startTime'=>$startTime))->andWhere('c.tPlanDate<=:endTime:',array('endTime'=>$endTime));

                }
                if($type){
//                $newBuilder->andWhere('c.iType=:iType:',array('iType'=>$type));
                    if($type==8){
                        $newBuilder->andWhere('c.iType in ({types:array})',array('types'=>[5,6,7]));
                    }else{
                        $newBuilder->andWhere('c.iType=:iType:',array('iType'=>$type));
                    }

                }
                //权限处理部分
                if($this->request->getQuery('ctype')!=2){ //当为2时，为单个项目只读显示，不用判断以下权限
                    $schools = School::getPower();//获取学校权限
//                    var_dump($schools);die;
                    if (!User::isAdmin() && $schools !== true) {
                        $conditionArr = [
                            'conditions' => [],
                            'bind'       => []
                        ];
                        if (count($schools) > 0) {
                            $conditionArr['conditions'][] = 'i.iSchoolId in ({schools:array})';
                            $conditionArr['bind']  = ['schools' => $schools];
//                            $builder->andWhere('', ['schools' => $schools]);
                        }
                        $auth = XhcustAuth::find([
                            'columns'    => 'iCUId',
                            'conditions' => 'bDelete=0 AND iAuthId=:iAuthId:',
                            'bind' => array('iAuthId' => Main::getLoginUserInfo('userId'))
                        ])->toArray();
                        if (count($auth) > 0) {
                            $authCuIds = array_values(array_filter(array_unique(array_column($auth, 'iCUId'))));
                            if ($authCuIds) {
                                $conditionArr['conditions'][] = 'p.iCUId in ({authCUIds:array})';
                                $conditionArr['bind']  = array_merge(['authCUIds' => $authCuIds], $conditionArr['bind']);
                            }
                        }
                        $conditionArr['conditions'][] = 'i.iCreateUserId = :nowId: ';
                        $conditionArr['bind']  =  array_merge(['nowId' => Main::getLoginUserInfo('userId')], $conditionArr['bind']);
                        $depArr = User::getExtraPower('dep', 'customer'); //获取客户的部门权限
                        if ($depArr) {
                            $userIds = array_values(array_filter(Hrm::getUserByDepId($depArr , true)));
                            if (count($userIds) > 0) {
                                $conditionArr['conditions'][] = 'i.iCreateUserId in ({users:array}) ';
                                $conditionArr['bind']  =  array_merge(['users' => $userIds], $conditionArr['bind']);
                            }
                        }
                        $conditionArr['conditions'][] = ' p.iChargeId=:iChargeId: OR c.iChargeId=:iChargeId: OR c.sExcuteIds=:iChargeId: ';
                        $conditionArr['bind']  =  array_merge(['iChargeId' => Main::getLoginUserInfo('userId')], $conditionArr['bind']);
//                        $newBuilder->andWhere('p.iChargeId=:iChargeId: OR c.iChargeId=:iChargeId: OR c.sExcuteIds=:iChargeId:',array('iChargeId'=>Main::getLoginUserInfo('userId')));
//                        if ( (!$depArr || count($userIds) <= 0 ) &&  count($schools) <= 0  ) { //没有客户 ，没有学校权限
//
//                        } else {
//                            $newBuilder->andWhere(implode(' or ', $conditionArr['conditions']), $conditionArr['bind']);
//                        }
                        $newBuilder->andWhere(implode(' or ', $conditionArr['conditions']), $conditionArr['bind']);

                    }
//                $userId=Main::getLoginUserInfo('userId');
//                if(!UserPower::checkUserPower('Bpm_Plan_All')){
//                    $newBuilder->andWhere('p.iChargeId=:iChargeId: OR c.iChargeId=:iChargeId: OR c.sExcuteIds=:iChargeId:',array('iChargeId'=>$userId));
//                }
                }

                $datas=$newBuilder->getQuery()->execute()->toArray();

//            if($this->request->getQuery('ctype')==2&&$datas[0]['realDate']!=null){ //当为2时，为单个项目只读显示，不用判断以下权限
//                $userId=Main::getLoginUserInfo('userId');
//                if(!$userId){
//                    return $this->response->redirect('Index/login');
//                }
//            }
//            var_dump($datas);die();
                if($datas==[]){
                    $toStuNum=0;
                    $toTeaNum=0;
                    $toClassNum=0;
                    $datas['numTotal']='<p style="display: inline" class=" fa-fw">&nbsp;&nbsp;&nbsp;&nbsp;学生:&nbsp;'.$toStuNum.'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;教师:&nbsp;'.$toTeaNum.'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;班级:&nbsp;'.$toClassNum.'</p>';
                    return json_encode($datas);
                }
                $newIds=[];
                $nCIds=[];
                foreach ($datas as $ksdata){ //按需求排序的字段
                    $newIds[]=$ksdata['iBPPId'];
                    $nCIds[]=$ksdata['iBPCId'];
                }
                $newIds=array_unique($newIds);
                $nCIds=array_unique($nCIds);


                $new=[];
                foreach ($newIds as $id){
                    $new[]=$id;
                }

                $newC=[];
                foreach ($nCIds as $id){
                    $newC[]=$id;
                }

                if($newIds!=null){
                    $builder->andWhere('p.iBPPId in ({ids:array})',array('ids'=>$new));
                }
                if($sort&&$order){
                    if($sort=="name"){
                        $sort='sSchoolName';
                        $builder->orderBy('i.'.$sort.' '.$order.'');
                    }else{
                        $builder->orderBy('p.'.$sort.' '.$order.'');
                    }
                }else{
                    $builder->orderBy('p.tCreateDate desc');
                }
            }

            if ($key) {
                $matchUserIds = XhhrmStaff::find([
                    'columns'    => 'iUserId',
                    'conditions' => 'bDelete = 0 and sStaffName like :key:',
                    'bind'       => ['key' => '%'.$key.'%']
                ])->toArray();
                $matchUserIds = array_values(array_filter(array_column($matchUserIds, 'iUserId')));
                $searchArr = [
                    'conditions' => ['i.sSchoolName Like :key:'],
                    'bind'       => ['key'=>'%'.$key.'%']
                ];
//                var_dump($matchUserIds);die;
                if ($matchUserIds) {
                    $bpIdArr = XHBpmPlanContent::find([
                        'columns'    => 'iBPPId',
                        'conditions' => 'bDelete = 0 and iChargeId in ({ids:array})',
                        'bind'       => ['ids' => $matchUserIds],
                        'group'      => 'iBPPId'
                    ])->toArray();
                    $bpIdArr = array_values(array_filter(array_unique(array_column($bpIdArr, 'iBPPId'))));
//                    var_dump($bpIdArr);die;
                    if ($bpIdArr) {
                        $searchArr['conditions'][] = ' p.iBPPId in ({searchIds:array}) ';
                        $searchArr['bind'] = array_merge($searchArr['bind'], ['searchIds' => $bpIdArr]);
                    }
                    $searchArr['conditions'][] = ' p.iChargeId in ({searchUserIds:array}) ';
                    $searchArr['bind'] = array_merge($searchArr['bind'], ['searchUserIds' => $matchUserIds]);
                }
//                var_dump($searchArr);die;
                $builder->andWhere(implode(' or ', $searchArr['conditions']), $searchArr['bind']);
            }



            $data=Main::runBuilderPaginator($builder,true);


            if($data['rows']==[]){
                return json_encode($data);
            }
            $ids=[];
            foreach ($data['rows'] as $index=>$row){
                $ids[]=$row['iBPPId'];
            }


            $plancBuilder = $this->modelsManager->createBuilder()
                ->columns('c.iBPCId,c.iBPPId,c.sNodeName,c.sExcuteDeps,c.sExcuteIds,c.iNodeState,
                        c.sRelatDeps,c.sRelatIds,c.tPlanDate,c.sQueDesc,c.sSolution,c.sExcProcess,c.tRealDate,c.iChargeId,c.iType,
                        c.mDesc,c.tCreateDate,c.iCreateUserId,c.tLastModifyDate,c.iLastModifyUserId,c.sOtherPhone,s.sSelfPhone,s.sStaffName as sChargeName')
                ->addFrom('Admin\Models\bpm\XHBpmPlanContent', 'c')
                ->leftJoin('Admin\Models\hrm\XhhrmStaff','c.iChargeId=s.iUserId','s')
                ->where('c.bDelete=0');
            if($all!=null&&$all!=0||$all==null){
                $plancBuilder->andWhere('c.iBPPId in ({ids:array})',array('ids'=>$ids))->orderBy('c.iSort');
            }
            if($sNodeName){
                if($all==0){
                    $plancBuilder->andWhere('c.sNodeName=:sNodeName:',array('sNodeName'=>$sNodeName))->andWhere('c.iBPPId in ({ids:array})',array('ids'=>$ids))->orderBy('c.iSort');
                }
            }else{
                if($all==0&&$all!=null){
                    $plancBuilder->andWhere('c.iBPCId in ({ids:array})',array('ids'=>$newC))->orderBy('c.iSort');
                }
            }

            $planContents=$plancBuilder->getQuery()->execute()->toArray();



            //在数据源上处理iChargeId
            Main::runUserNameById($planContents, array('iCreateUserId'=>'iCreateUserId','iLastModifyUserId'=>'iLastModifyUserId'), true);


            $iBPPIds=$builder->columns('p.iBPPId')->getQuery()->execute()->toArray();
            $iBds=[];
            foreach ($iBPPIds as $index=>$row){
                $iBds[]=$row['iBPPId'];
            }
            //--------------------------流转单预计数据处理--------------------------
            $transList=XHBpmTransList::find([
                'conditions'=>'bDelete=0 AND iBPPId in ({ids:array})',
                'bind'=>array('ids'=>$iBds)
            ]);
            $transList=$transList->toArray();
            $planNum = [
                'stuNum' => 0,
                'tchNum' => 0,
                'classNum' => 0,
            ];
            foreach ($transList as $tran){
                $planNum['stuNum']+=($tran['iStudentNum']==null?0:$tran['iStudentNum']);
                $planNum['tchNum']+=($tran['iTeacherNum']==null?0:$tran['iTeacherNum']);
                $planNum['classNum']+=($tran['iClassNum']==null?0:$tran['iClassNum']);
            }
//            $transList=XHBpmTransList::find([
//                'conditions'=>'bDelete=0 AND iBPPId in ({ids:array})',
//                'bind'=>array('ids'=>$ids)
//            ]);
//            $transList = $transList->toArray();
            Main::runUserNameById($transList,['iLastModifyUserId'=>'iLastModifyUserId'],true);
            $transList = array_column($transList,null,'iBPPId');
            $tabInfoArr = [];
            if ($iBds) {
                $applyTabArr = XHImsApplyTablet::find([
                    'columns' => 'iRTId, iBPPId,iState,iType,tCreateDate',
                    'conditions' => 'bDelete = 0',
                    'bind'       => ['ids' => $iBds],
//                    'group'   => 'iBPPId'
                ])->toArray();
                if ($applyTabArr) {
                    foreach ($applyTabArr as $applyTab) {
                        $tabItem = Tool::getValue($tabInfoArr, $applyTab['iBPPId'],  []);
                        $tabType = Tool::getValue($tabItem, $applyTab['iType'], '');
                        if (!$tabType) {
                            $tabInfoArr[$applyTab['iBPPId']][$applyTab['iType']] = [
                                'color' => $applyTab['iState'] != 3 ? 'grey' : '#2baab1',
                                'date'  => $applyTab['tCreateDate']
                            ];
                        } else {
                            if ($tabType && $applyTab['iState'] != 3) {
                                $tabInfoArr[$applyTab['iBPPId']][$applyTab['iType']] = [
                                    'color' => 'grey',
                                    'date'  =>  $applyTab['tCreateDate']
                                ];
                            }
                        }
                    }
                }
//                $applyTabArr = array_column($applyTabArr, 'iRTId', 'iBPPId');
            }
            foreach ($data['rows'] as $index=>$row){
                $item=[];
                $item=$row;
                if(isset($transList[$row['iBPPId']])){
                    $icon = 'fa-file';
                    if ($transList[$row['iBPPId']]['bUpdate']) {
                        $icon = 'fa-file-archive-o';
                    }
                    if(!$this->transCheck($transList[$row['iBPPId']])){
                        $item['file']='<i class="fa '.$icon.'" title="流转单未填写完整, 最后修改人'.$transList[$row['iBPPId']]['iLastModifyUserId'].',最后修改时间：'.$transList[$row['iBPPId']]['tLastModifyDate'].'" style="color:red;"></i>';
                    }else{
                        $item['file']='<i class="fa '.$icon.'" title="流转单,最后修改人'.$transList[$row['iBPPId']]['iLastModifyUserId'].',最后修改时间：'.$transList[$row['iBPPId']]['tLastModifyDate'].'" style="color:#2baab1;"></i>';
                    }
                }else{
                    $item['file']='';
                }
                if($item['iState']!=null){
                    if($item['iState']==1){
                        $item['iState']='<i class="fa fa-play" title="启动" style="color:#2baab1;"></i>';
                    }else if($item['iState']==2){
                        $item['iState']='<i class="fa fa-circle" title="未启动" style="color:grey;"></i>';
                    }else{
                        $item['iState']='<i class="fa fa-pause" title="暂停" style="color:red;"></i>';
                    }

                }else{
                    $item['iState']='';
                }
                $item['keyId']='P-'.$row['iBPPId'];
                $item['realId']=$row['iBPPId'];
                $item['type']=1;
                $item['lock']= $row['tPlanDate'] ? '<i class="fa fa-lock fa-lg" title="已确认" style="color:grey;"></i>' : '';
                if (isset($tabInfoArr[$row['iBPPId']])) {
                    foreach ($tabInfoArr[$row['iBPPId']] as $tabType => $tabInfo) {
                        if ($tabType == 1) {
                            $item['lock'] .= '<i class="fa fa-tablet fa-lg" title="流程计划已申请平板领用,创建时间:'.$tabInfo['date'].'" style="color:'.$tabInfo['color'].';"></i>&nbsp;';
                        }
                        if ($tabType == 2) {
                            $item['lock'] .= '<i class="fa fa-mobile fa-lg" title="学生机已申请平板领用,创建时间:'.$tabInfo['date'].'" style="color:'.$tabInfo['color'].';"></i>&nbsp;';
                        }
                    }
                }
                $item['name']=$row['sSchoolName'];
                $item['tCreateDate']=$row['tCreateDate'];
                $item['iCreateUserId']=$row['iCreateUserId'];
                $item['tLastModifyDate']=$row['tLastModifyDate'];
                $item['iLastModifyUserId']=$row['iLastModifyUserId'];
                $childrens=[];
                $totalProcess=0;
                $i=0;
                $mainCss='green';
                foreach ($planContents as $pcontent){
                    if($pcontent['iBPPId']==$row['iBPPId']){
                        $i++;
                        $child=[];
                        $child=$pcontent;
                        $css=$this->getColorType($row['tStartTime'],$pcontent['tPlanDate'],$pcontent['tRealDate']);
                        $mainCss=$this->powerCss($css,$mainCss);
                        if($child['sExcProcess']==null){
                            $totalProcess+=0;
                            $child['sExcProcess']='<div class="progress"><div class="progress-bar '.$css.'" style="width: 100%;"></div></div>';
                        }else{
                            $totalProcess+=$child['sExcProcess'];
                            if($child['tRealDate']!=null){
                                $child['sExcProcess']=100;
                            }
                            $child['sExcProcess']='<div class="progress"><div class="progress-bar '.$css.'" style="width: '.$child['sExcProcess'].'%;"></div></div>';
                        }
                        $this->saveType($pcontent['iBPCId'],$child['iType'],$this->getType($css));
                        $child['keyId']='C-'.$pcontent['iBPCId'];
                        $child['realId']=$pcontent['iBPCId'];
                        $child['name']=$pcontent['sNodeName'];
                        $child['type']=2;
                        $child['sExcuteDeps']=$this->getDepNames($pcontent['sExcuteDeps'],$depEnum);
                        $child['sRelatDeps']=$this->getDepNames($pcontent['sRelatDeps'],$depEnum);

                        if($pcontent['iNodeState']==1){
                            $child['lock']='<i class="fa fa-check" title="已完成" style="color:#2baab1;"></i>';
                        }else{
                            $child['lock']='';
                        }

                        if(isset($child['sChargeName'])){
                            $child['sChargeName']=$child['sChargeName'].'('.$child['sSelfPhone'].')';
                        }
                        if($type==$this->getType($css)&&$pcontent['iBPPId']==$openId){
                            $childrens[]=$child;
                        }else if($type!=null&&$pcontent['iBPPId']==$openId){

                        }else if($type!=null&&$pcontent['iBPPId']!=$openId){
                            $childrens[]=$child;
                        }else{
                            $childrens[]=$child;
                        }
                    }
                }
                if($i!=0){
                    $totalProcess=intval($totalProcess/$i);
                }else{
                    $totalProcess=100;
                }

                $item['sExcProcess']='<div class="progress"><div class="progress-bar '.$mainCss.'" style="width: '.$totalProcess.'%;"></div></div>';

                if($childrens!=[]){
                    $item['children']=$childrens;
                    if($openId!=null){
                        if($openId!=$row['iBPPId']){
                            $item['state']='closed';
                        }else{
                            $item['state']='open';
                        }
                    }else{
                        $item['state']='closed';
                    }

                }
                if($all!=null&&$all==0){
                    $item['state']='open';
                }
                $data['rows'][$index]=$item;
            }

            Main::runUserNameById($data['rows'], array('iCreateUserId'=>'iCreateUserId','iLastModifyUserId'=>'iLastModifyUserId'), true);

            foreach ($data['rows'] as $index=>$row){
                if(isset($row['sChargeName'])){
                    $ifChanged = XHBpmChargerLog::findFirst([
                        'conditions' => 'bDelete = 0 and iBPPId = '.$row['iBPPId']
                    ]);
                    if (!empty($ifChanged)) {
                        $data['rows'][$index]['sChargeName']="<div style = 'color:red;'>".$row['sChargeName'].'('.$row["sSelfPhone"].')';
                    } else {
                        $data['rows'][$index]['sChargeName']="<div>".$row['sChargeName'].'('.$row["sSelfPhone"].')';
                    }

                }
            }
            $applyInfo = [
                'realClassNum' => 0,
                'realTchNum' => 0,
                'realStuNum' => 0
            ];
//            流转单实际数据处理
            if ($iBds) {

                $applyTabArr = XHImsApplyTablet::find([
                    'conditions' => 'bDelete = 0 and iBPPId in ({ids:array}) and iState = 3',
                    'bind'       => ['ids' => $iBds],
                    'order'      => 'iBPPId'
                ])->toArray();
                $retTabArr = XHImsReturnTab::find([
                    'conditions' => 'bDelete = 0 and iBPPId in ({ids:array}) and iState = 3',
                    'bind'       => ['ids' => $iBds],
                    'order'      => 'iBPPId'
                ])->toArray();

                if ($applyTabArr) {
                    $applyTabArrSortById = [];  //申领合并相同的iBBPId
                    foreach ($applyTabArr as $applyTab) {
                        $applyTabArrSortById[$applyTab['iBPPId']][] = $applyTab;
                    }
                    foreach ($applyTabArrSortById as $bpId => $applyTabRecordArr) {
                        $classArr = [];
                        $studentArr = [];
                        foreach ($applyTabRecordArr as $applyTabRecord) { //同一个iBBPId 领用记录循环
                            if ($applyTabRecord['iState'] != 3) {
                                continue;
                            }
                            if ($applyTabRecord['iType'] == 1) {
                                $applyInfo['realStuNum'] += Tool::getValue($applyTabRecord, 'iStuNum', 0);
                                $applyInfo['realTchNum'] += Tool::getValue($applyTabRecord, 'iTchNum', 0);
                                $class = Tool::getValue($applyTabRecord, 'sClasses', '');
                                if ($class) {
                                    $class = explode(',', $class);
                                    $classArr = array_merge($classArr, $class);
                                }
                            } elseif ($applyTabRecord['iType'] == 2) {
                                $applyInfo['realStuNum'] += Tool::getValue($applyTabRecord, 'iStuNum', 0);
                                $students = explode(',', $applyTabRecord['sStudents']);
                                if ($students) {
                                    $studentArr = array_merge($students, $studentArr);
                                }
                            } elseif ($applyTabRecord['iType'] == 3) {
                                $applyInfo['realTchNum'] += Tool::getValue($applyTabRecord, 'iTchNum', 0);
                            }
                        }
                        if ($studentArr) {
                            $studentArr = array_values(array_unique(array_filter($studentArr)));
                            $classSql = "select sAdClsName from XHSys_User where iUserId in (".implode(',', $studentArr).")
                                  group by sAdClsName ";
                            $class = $this->db->fetchAll($classSql);
                            if ($class) {
                                $class = array_column($class, 'sAdClsName');
                                if ($class) {
                                    $classArr = array_merge($classArr, $class);
                                }
                            }
                        }
                        $applyInfo['realClassNum'] += count(array_values(array_unique(array_filter($classArr))));
                    }
                }

                if ($retTabArr) {
                    foreach ($retTabArr as $retTab) {
                        if ($retTab['iState'] != 3) {
                            continue;
                        }
                        if (!is_array($retTab['mData'])) {
                            $retTab['mData'] = $retTab['mData'] ? unserialize($retTab['mData']) : [];
                        }
                        if ($retTab['iSource'] == 1) { //设备申领
                            foreach ($retTab['mData'] as $row) {
                                $devType = Tool::getValue($row, 'iReceivePurpose', '');
                                if ($devType &&  $devType == '教师机') {
                                    $applyInfo['realTchNum'] -= 1;
                                }
                            }
                        } elseif ($retTab['iSource'] == 2) { //学生列表
                            $applyInfo['realStuNum'] -= count($retTab['mData']);
                        } elseif ($retTab['iSource'] == 3) { //教师列表
                            $applyInfo['realTchNum'] -= count($retTab['mData']);
                        }
                    }
                }
//                $this->view->setVar('applyInfo', $applyInfo);
            }
            $data['footer'] = [
                [
                    'name' => '学生数',
                    'tPlanDate' => '预计',
                    'tRealDate' => @$planNum['stuNum'],
                    'sExcProcess' => '实际',
                    'sChargeName' => @$applyInfo['realStuNum']
                ],
                [
                    'name' => '教师数',
                    'tPlanDate' => '预计',
                    'tRealDate' => @$planNum['tchNum'],
                    'sExcProcess' => '实际',
                    'sChargeName' => @$applyInfo['realTchNum']
                ],
                [
                    'name' => '班级数',
                    'tPlanDate' => '预计',
                    'tRealDate' => @$planNum['classNum'],
                    'sExcProcess' => '实际',
                    'sChargeName' => @$applyInfo['realClassNum']
                ],
            ];

//            $data['numTotal']='<p style="display: inline" class=" fa-fw">&nbsp;&nbsp;&nbsp;&nbsp;学生:&nbsp;'.$toStuNum.'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;教师:&nbsp;'.$toTeaNum.'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;班级:&nbsp;'.$toClassNum.'</p>';


            return json_encode($data);
        }catch (\Exception $e){
            return $this->sendErrorResponse(500 ,$e->getMessage());
        }

    }

    /**
     * 导出流程计划流转单
     *
     * create by xjq 20180707
     */
    public function exportPlanTransAction(){
        $this->view->disable();
        try{
            $startTime = $this->request->getQuery('startTime','string') ;
            $endTime  = $this->request->getQuery('endTime','string')  ;
            $iState = $this->request->getPost('iState','string');
            $key = $this->request->getQuery('key','string');
            $province = $this->request->getQuery('province','string');
            $citys = $this->request->getQuery('city','string');
            if($citys!=null){
                $citys= array_values(array_filter(explode(',',$citys)));
            }else{
                $citys=[];
            }
            $builder = $this->modelsManager->createBuilder()
                ->columns('p.iBPPId,i.iSchoolId')
                ->addFrom('Admin\Models\bpm\XHBpmPlan', 'p')
                ->leftJoin('Admin\Models\crm\XhcustInfo', 'i.iCUId=p.iCUId', 'i')
                ->leftJoin('Admin\Models\bpm\XHBpmPlanContent','p.iBPPId=c.iBPPId ','c')
                ->where('p.bDelete=0');
            $startTime = $startTime ?: '1970-01-01';
            $endTime   = $endTime   ?: date('Y-m-d',time());
            if($startTime&&$endTime) {
                $builder->andWhere('c.tPlanDate>=:startTime:', array('startTime' => $startTime))->andWhere('c.tPlanDate<=:endTime:', array('endTime' => $endTime));
            }
            if($iState){
                $builder->andWhere('p.iState=:iState:',array('iState'=>$iState));
            }
            if($key){
                $builder->andWhere('i.sSchoolName Like :key:',array('key'=>'%'.$key.'%'));
            }
            if($province&&$province!='全部省'){
                $builder->andWhere('i.sProvinceName=:province:',array('province'=>$province));
            }
            if($citys!=[]&&$citys[0]!='全部市'){
                $builder->andWhere('i.sCityName in ({names:array})',array('names'=>$citys));
            }

            $schools = School::getPower();//获取学校权限
            if (!User::isAdmin() && $schools !== true) {
                $conditionArr = [
                    'conditions' => [],
                    'bind' => []
                ];
                if (count($schools) > 0) {
                    $conditionArr['conditions'][] = 'i.iSchoolId in ({schools:array})';
                    $conditionArr['bind'] = ['schools' => $schools];
//                            $builder->andWhere('', ['schools' => $schools]);
                }
                $auth = XhcustAuth::find([
                    'columns'    => 'iCUId',
                    'conditions' => 'bDelete=0 AND iAuthId=:iAuthId:',
                    'bind' => array('iAuthId' => Main::getLoginUserInfo('userId'))
                ])->toArray();
                if (count($auth) > 0) {
                    $authCuIds = array_values(array_filter(array_unique(array_column($auth, 'iCUId'))));
                    if ($authCuIds) {
                        $conditionArr['conditions'][] = 'p.iCUId in ({authCUIds:array})';
                        $conditionArr['bind']  = array_merge(['authCUIds' => $authCuIds], $conditionArr['bind']);
                    }
                }
                $depArr = User::getExtraPower('dep', 'customer'); //获取客户的部门权限
                if ($depArr) {
                    $userIds = array_values(array_filter(Hrm::getUserByDepId($depArr, true)));

                    if (count($userIds) > 0) {
                        $conditionArr['conditions'][] = 'i.iCreateUserId in ({users:array})';
                        $conditionArr['bind'] = array_merge(['users' => $userIds], $conditionArr['bind']);
                    }
                }
                if ((!$depArr || count($userIds) <= 0) && count($schools) <= 0) { //没有客户 ，没有学校权限
                    $builder->andWhere('p.iChargeId=:iChargeId: OR c.iChargeId=:iChargeId: OR c.sExcuteIds=:iChargeId:', array('iChargeId' => Main::getLoginUserInfo('userId')));
                } else {
                    $builder->andWhere(implode(' or ', $conditionArr['conditions']), $conditionArr['bind']);
                }
            }
            $ids  = array_filter(array_column($builder->getQuery()->execute()->toArray(), 'iSchoolId', 'iBPPId'));
            if (!$ids) {
                return $this->sendErrorResponse(500 ,'没有需要导出的数据');
            }
            $source = XHBpmTransList::find([
                'conditions' => 'bDelete = 0 and iBPPId in ({ids:array})',
                'bind'       => ['ids' => array_keys($ids)]
            ])->toArray();
            $areaArr = XhcustInfo::find([
                'columns'    => 'iSchoolId,sProvinceName,sCityName,sCountyName ',
                'conditions' => 'bDelete = 0 and iSchoolId in ({ids:array}) ',
                'bind'       => ['ids' => array_values($ids)]
            ])->toArray();
            $areaArr = array_column($areaArr, null, 'iSchoolId');
            foreach ($source as &$row) {
                $schoolId = $ids[$row['iBPPId']];
                if ($schoolId) {
                    $area = Tool::getValue($areaArr, $schoolId, ['sProvinceName' => '', 'sCityName' => '', 'sCountyName' => '']);
                    $row['sProvinceName'] = $area['sProvinceName'];
                    $row['sCityName']     = $area['sCityName'];
                    $row['sCountyName']   = $area['sCountyName'];
                } else {
                    $row['sProvinceName'] = '';
                    $row['sCityName']     = '';
                    $row['sCountyName']   = '';
                }
            }

//            $data = array_column($data, null, 'iBPPId');
            Main::runUserNameById($source, ['iOperateId' => 'iOperateId'], true);

            $title = [
                'sSchoolName'=>'学校名称',
                'sProvinceName' => '省',
                'sCityName' => '县',
                'sCountyName' => '市',
                'sClasses' => '班级',
                'iClassNum' => '班级数量',
                'iTeacherNum' => '教师人数',
                'iStudentNum' => '学生人数',
                'iTchRoom' => '教室数量',
                'iOfficeNum' => '办公室数量',
                'iOperateId' => '运营负责人',
                'sSchNetChargeName' => '学校网络负责人',
                'sSchNetChargePhone' => '网络负责人电话',
                'sOfficeAddress' => '办公室位置',
                'iOtherNum' => ' 其他场所数量',
                'mOtherAddress' => '其他场所说明'
            ];
            $data = [];
            foreach ($source as $key => $row) {
                foreach ($title as $filed => $name) {
                    $data[$key][$filed] = isset($row[$filed]) ? $row[$filed] : '';
                }
            }
            $fileName = '流转单_' . time();
            Tool::exportExcelOnline($fileName, $title, $data, 'xlsx', ['autoWidth' => true,'header'=>['title'=>'流转单']]);
        }catch (\Exception $e){
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }


    public function powerCss($css,$pcss){
        if($css=='bigRed'||$css=='red'){
            $css='yellow';
        }
        if($css=='gray'){
            $css='lightblue';
        }
        $power=[ 'yellow'=>4,'lightblue'=>3,'blue'=>2,'green'=>1];
        if($power[$pcss]<$power[$css]){
            return $css;
        }else{
            return $pcss;
        }
    }



    /**
     * 导出excel
     * created by dale 2017/8/29
     */
    public function exportPlanAction(){
        $this->view->disable();
        $type   = $this->request->getQuery('type','string'); //所属类型
        $startTime = $this->request->getQuery('startTime','string') ;
        $endTime  = $this->request->getQuery('endTime','string')  ;
        $sNodeName = $this->request->getQuery('sNodeName','string') ;

        $tsort = $this->request->getQuery('tsort','string');
        $key = $this->request->getQuery('key','string');
        $province = $this->request->getQuery('province','string');
        $city = $this->request->getQuery('city','string');
        $sort = $this->request->getPost('sort','string');
        $order = $this->request->getPost('order','string');

        $builder = $this->modelsManager->createBuilder()
            ->columns('p.iBPPId,p.iCUId,p.tStartTime,p.iChargeId,p.tPlanDate,p.tRealDate,p.mDesc,p.tCreateDate,p.iCreateUserId,p.tLastModifyDate,p.iLastModifyUserId,i.sSchoolName,i.sProvinceName,i.sCityName')
            ->addFrom('Admin\Models\bpm\XHBpmPlan', 'p')
            ->leftJoin('Admin\Models\crm\XhcustInfo', 'i.iCUId=p.iCUId', 'i')
            ->where('p.bDelete=0');
        $depEnum=XhhrmDepart::getDepEnum();

        if($province&&$province!='全部省'){
            $builder->andWhere('i.sProvinceName=:province:',array('province'=>$province));
        }
        if($city&&$city!='全部市'){
            $builder->andWhere('i.sCityName=:city:',array('city'=>$city));
        }

        if($tsort==null){
            if($sort&&$order){
                if($sort=="name"){
                    $sort='sSchoolName';
                    $builder->orderBy('i.'.$sort.' '.$order.'');
                }else{
                    $builder->orderBy('p.'.$sort.' '.$order.'');
                }
            }else{
                $builder->orderBy('p.tCreateDate desc');
            }

        }


        if($sNodeName){
            $builder->leftJoin('Admin\Models\bpm\XHBpmPlanContent','p.iBPPId=c.iBPPId ','c')->columns('p.iBPPId,p.iCUId,p.tStartTime,p.iChargeId,p.tPlanDate,p.tRealDate,p.mDesc,p.tCreateDate,p.iCreateUserId,p.tLastModifyDate,p.iLastModifyUserId,i.sSchoolName,i.sProvinceName,i.sCityName,c.tPlanDate as cPlanDate ,c.iType as cType ,c.iBPCId')
                ->andWhere('c.sNodeName=:sNodeName:',array('sNodeName'=>$sNodeName));

            if($startTime==null&&$endTime){
                $startTime='1970-01-01';
            }
            if($endTime==null&&$startTime){
                $endTime=date('Y-m-d',time());
            }
            if($startTime&&$endTime){
                $builder->andWhere('c.tPlanDate>=:startTime:',array('startTime'=>$startTime))->andWhere('c.tPlanDate<=:endTime:',array('endTime'=>$endTime));

            }
            if($type){
                $builder->andWhere('c.iType=:iType:',array('iType'=>$type));
            }
            if($tsort==2){
                if($sort&&$order){
                    if($sort=="name"){
                        $sort='sSchoolName';
                        $builder->orderBy('c.tPlanDate DESC'.',i.'.$sort.' '.$order.'');
                    }else{
                        $builder->orderBy('c.tPlanDate DESC'.',p.'.$sort.' '.$order.'');
                    }
                }else{
                    $builder->orderBy('c.tPlanDate DESC');
                }

            }else if($tsort==1){
                if($sort&&$order){
                    if($sort=="name"){
                        $sort='sSchoolName';
                        $builder->orderBy('c.tPlanDate '.',i.'.$sort.' '.$order.'');
                    }else{
                        $builder->orderBy('c.tPlanDate '.',p.'.$sort.' '.$order.'');
                    }
                }else{
                    $builder->orderBy('c.tPlanDate ');
                }
            }

        }
        if($key){
            $builder->andWhere('i.sSchoolName Like :key:',array('key'=>'%'.$key.'%'));
        }
        $data=$builder->getQuery()->execute()->toArray();

        $ids=[];
        foreach ($data as $index=>$row){
            $ids[]=$row['iBPPId'];
        }

        $planContents=XHBpmPlanContent::find([
            'conditions'=>'bDelete=0 AND iBPPId in ({ids:array})',
            'bind'=>array('ids'=>$ids),
            'order'=>'iSort'
        ]);


        $planContents=$planContents->toArray();

        //在数据源上处理iChargeId
       // Main::runUserNameById($planContents, array('iChargeId'=>'sChargeName','iCreateUserId'=>'iCreateUserId','iLastModifyUserId'=>'iLastModifyUserId'), true);


         $newArray=[];
        foreach ($data as $index=>$row){
            $item=[];
            $item=$row;
            $item['keyId']='P-'.$row['iBPPId'];
            $item['realId']=$row['iBPPId'];
            $item['type']=1;
            $item['name']=$row['sSchoolName'];
            $item['tCreateDate']=$row['tCreateDate'];
            $item['iCreateUserId']=$row['iCreateUserId'];
            $item['tLastModifyDate']=$row['tLastModifyDate'];
            $item['iLastModifyUserId']=$row['iLastModifyUserId'];
            $childrens=[];
            $totalProcess=0;
            $i=0;
            foreach ($planContents as $pcontent){
                if($pcontent['iBPPId']==$row['iBPPId']){
                    $i++;
                    $child=[];
                    $child=$pcontent;
                    $css=$this->getColorType($row['tStartTime'],$pcontent['tPlanDate'],$pcontent['tRealDate']);
                    if($child['sExcProcess']==null){
                        $totalProcess+=0;
                        $child['sExcProcess']=100;
                    }else{
                        $totalProcess+=$child['sExcProcess'];
                        if($child['tRealDate']!=null){
                            $child['sExcProcess']=100;
                        }
                        $child['sExcProcess']=$child['sExcProcess'];
                    }
//                    $this->saveType($pcontent['iBPCId'],$this->getType($css));
                    $child['keyId']='C-'.$pcontent['iBPCId'];
                    $child['realId']=$pcontent['iBPCId'];
                    $child['name']=$pcontent['sNodeName'];
                    $child['type']=2;
                    $child['sExcuteDeps']=$this->getDepNames($pcontent['sExcuteDeps'],$depEnum);
                    $child['sRelatDeps']=$this->getDepNames($pcontent['sRelatDeps'],$depEnum);
                    $childrens[]=$child;

                }
            }
            $totalProcess=intval($totalProcess/$i);
            $item['sExcProcess']=$totalProcess;
            $newArray[]=$item;
            foreach ($childrens as $child){
                $newArray[]=$child;
            }
            //$data[$index]=$item;
        }
        Main::runUserNameById($newArray, array('iChargeId'=>'sChargeName','iCreateUserId'=>'iCreateUserId','iLastModifyUserId'=>'iLastModifyUserId'), true);
        //var_dump($newArray);die();
        $title = [
            'sSchoolName'=>'学校名称',
            'name' => '名称',
            'tStartTime' => '发起时间',
            'sExcuteDeps' => '实施部门',
            'sRelatDeps' => '相关部门',
            'tPlanDate' => '预计完成时间',
            'sQueDesc' => '问题描述',
            'sSolution' => '应对方案',
            'sExcProcess' => '执行进度',
            'tRealDate' => '实际完成时间',
            'sChargeName' => '总负责人/负责人',
            'mDesc' => '备注',
            'tCreateDate' => '创建时间',
            'iCreateUserId' => '创建用户',
            'tLastModifyDate' => '最后修改时间',
            'iLastModifyUserId' => '最后修改用户',
        ];
        $data = [];
        foreach ($newArray as $key => $row) {
            foreach ($title as $filed => $name) {
                $data[$key][$filed] = isset($row[$filed]) ? $row[$filed] : '';
            }
        }
        $fileName = '流程计划_' . Main::getLoginUserInfo('userName');
        Tool::exportExcelOnline($fileName, $title, $data);
    }



    public function saveType($iBPCId,$iType,$type){

        if($iType==null||$iType!=$type){
            $obj=XHBpmPlanContent::findFirst([
                'conditions'=>'bDelete=0 AND iBPCId=:iBPCId:',
                'bind'=>array('iBPCId'=>$iBPCId)
            ]);
            $obj->iType=$type;
            $obj->save();
        }

    }


    public function checkFile($iBPPId,$tranList){

        foreach ($tranList as $trans){
            if($trans['iBPPId']==$iBPPId){

                return true;
            }
        }
        return false;


    }
    /**
     *  删除plan记录
     *
     * @return string
     * created by dale 2017/8/22
     */
    public function delPlanAction(){
        UserPower::checkUserPower('Bpm_Plan_Del') or die('缺少权限');
        $id = $this->request->getPost('id','string');
        $obj    = XHBpmPlan::findFirst($id);
        $appTab = XHImsApplyTablet::findFirst([
            'conditions' => 'bDelete = 0 and iBPPId = :iBPPId:',
            'bind'       => ['iBPPId' => $id]
        ]);
        if ($appTab) {
          return $this->sendErrorResponse(500, '该流程计划，关联了设备申领无法删除');
        }
        $obj->bDelete = 1;
        $result=$obj->save();
//        $UserId=Main::getLoginUserInfo('userId');
        if($result){
            $pcs=XHBpmPlanContent::find([
                'conditions'=>'bDelete=0 AND iBPPId =:id:',
                'bind'=>array('id'=>$obj->iBPPId),
            ]);
            foreach ($pcs as $pc){
                $pc->bDelete = 1;
                if(!$pc->save()){
                    return $this->sendErrorResponse(500, '删除失败');
                }
            }
            $re = XhProjectHistory::delData($id);
            if (!$re) {
                return $this->sendErrorResponse(500, '删除失败');
            }
            return $this->sendSuccessResponse('删除成功');
        } else {
            return $this->sendErrorResponse(500, '删除失败');
        }
    }


    /**
     * 锁定content ,并将最长的预计完成时间显示在主记录上
     *
     * @param bool $unlock
     * @return string
     *
     * create by dale 20170822
     * rebuild by ck 20170922    添加解锁，锁定时添加事务
     */
    public function lockContentAction($unlock = false) {
        $id = $this->request->getPost('id','string');
        if (!$id) {
            return '缺少id参数！';
        }
        try {
            $this->db->begin();
            $plan = XHBpmPlan::findFirst($id);
            if (!$plan) {
                throw new \Exception('找不到该记录！');
            }
            if (!$unlock) {
                if ($plan->tPlanDate) {
                    return 'success';
                }
                //检查日期是否完成
                $checkDate = XHBpmPlanContent::findFirst([
                    'conditions' => 'bDelete = 0 AND iBPPId = :id: AND IFNULL(tPlanDate, "") = ""',
                    'bind'       => ['id' => $id]
                ]);
                if ($checkDate) {
                    throw new \Exception('请检查计划日期是否填写完毕');
                }
                //获取最大日期并填充
                $plan->tPlanDate = XHBpmPlanContent::findFirst([
                    'columns'    => 'MAX(tPlanDate) as maxDate',
                    'conditions' => 'bDelete = 0 AND iBPPId = :id:',
                    'bind'       => ['id' => $id]
                ])->toArray()['maxDate'];
                $lockStatus = 1;
            }
            else {
                if (!$plan->tPlanDate) {
                    return 'success';
                }
                $plan->tPlanDate = null;
                $lockStatus = 0;
            }
            //批量更新
            $result = $this->modelsManager->executeQuery('update \\Admin\\Models\\bpm\\XHBpmPlanContent set bLock = :status: where bDelete = 0 AND iBPPId = :id:', ['id' => $id, 'status' => $lockStatus]);
            if (!$result) {
                throw new \Exception('操作失败！');
            }
            if (!$plan->save()) {
                throw new \Exception('操作失败！');
            }
            $this->db->commit();
            return 'success';
        }
        catch (\Exception $e) {
            $this->db->rollback();
            return $e->getMessage();
        }

//        $id = $this->request->getPost('id','string');
//        $obj=XHBpmPlan::findFirst([
//            'conditions'=>'bDelete=0 AND iBPPId =:id:',
//            'bind'=>array('id'=>$id),
//        ]);
//        if($obj->tPlanDate!=null){
//            return 'success';
//        }
//
//        $objs = XHBpmPlanContent::find([
//            'conditions'=>'bDelete=0 AND iBPPId =:id:',
//            'bind'=>array('id'=>$id),
//            'order'=>'tPlanDate'
//        ]);
//        foreach ($objs as $oneObj){  //循环处理冻结
//            if($oneObj->tPlanDate==null){
//                return '请检查计划日期是否填写完毕';
//            }
//            $oneObj->bLock = 1;
//            if(!$oneObj->save()){
//               return 'fail';
//            }
//        }
//        $arrays=$objs->toArray();
//        $last=end($arrays);
//        $obj->tPlanDate=$last['tPlanDate'];
//        if($obj->save()){
//            return 'success';
//        }else{
//            return 'fail';
//        }
    }

    /**
     * 获取部门人员信息
     */
    public function getDepStaffEnumAction(){
        $this->view->disable();
        $deps= XhhrmDepart::find([
            'columns'=>'iDepId,sDepName',
            'conditions'=>'bDelete=0 AND iParentId=:iParentId:',
            'bind'=>array('iParentId'=>0),
        ]);
        $ids=[];
        foreach ($deps as $dep){
            $id=[];
            $id['id']=$dep->iDepId;
            $id['text']=$dep->sDepName;
            $ids[]=$id;
        }
        $array=[];
        foreach ($ids as $id){
            $item=[];
            $item['id']='D-'.$id['id'];
            $item['text']=$id['text'];
            $item['iconCls']='fa fa-group';
            $staffs=XhhrmStaff::find([
                'columns'=>'iStaffId,sStaffName,iUserId',
                'conditions'=>"bDelete=0 AND sDepIds like :id:",
                'bind'=>array("id"=>'%,'.$id['id'].',%')
            ]);
            $staffs=$staffs->toArray();
            if($staffs!=null){
                // var_dump($staffs);
                $childrens=[];
                foreach ($staffs as $staff){
                    $child=[];
                    $child['id']=$staff['iUserId'];
                    $child['iconCls']='fa fa-user';
                    $child['text']=$staff['sStaffName'];
                    $childrens[]=$child;
                }
                $item['children']=$childrens;
                $item['state']="closed";
            }
            $array[]=$item;
        }
        return json_encode($array);
    }

    /**
     * 获取部门名字
     * @param $ids
     * @return array|string
     * created by dale 2017/8/23
     */
    public function getDepNames($ids,$depEnum){
        if($ids==''){
            return '';
        }
        $ids=explode(',', $ids);
        if($ids==[]){
            return '';
        }
        $names=[];
        foreach ($ids as $id){
            $names[]= Tool::getValue($depEnum, $id, '');
        }
        $names=implode(',',$names);
        return $names;
    }

    public function planProgressAction(){
        UserPower::checkUserPower('Bpm_Progress') or die('缺少权限');
        $this->view->pick('plan/planProgress');
        Assets::importJs('js/plan/planProgress.js');
        Assets::easyUI();
        $this->di->get('assets')->addCss('bpm/css/Color.css');
        Assets::importMainJs('assets/xh/xhTop.js');
        Template::exists('planProgress', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));
        $iTPId=XHBpmTemplate::findFirst([
            'columns'=>'iTPId',
            'conditions'=>'bDelete=0',
        ]);
        $iTPId=$iTPId->iTPId;
        $arrs=XHBpmNode::find([
            'columns'=>'iNodeId,sNodeName',
            'conditions'=>'bDelete=0 AND iTPId=:iTPId:',
            'bind'=>['iTPId'=>$iTPId],
            'order'=>'iSort',
        ]);
        $arrs=array_column($arrs->toArray(),'sNodeName','sNodeName');
        $provinces = \Admin\Models\overt\XhovertAreainfo::getChildArea();

        $this->view->setVars(array(
            'List' => Template::createList('List', 'planProgress', [
//                'searchToolbar' => Template::createSearchToolBar($listSearchArr, false),
                'checkbox' => false,
            ]),
            'nodes'=>$arrs,
            'provinces'=>$provinces

        ));
    }

    public function getPlanProgressAction(){
        $type   = $this->request->getPost('type','string'); //所属类型
        $startTime = $this->request->getPost('startTime','string') ;
        $endTime  = $this->request->getPost('endTime','string')  ;
        $sNodeName = $this->request->getPost('sNodeName','string') ;
        $tsort = $this->request->getPost('tsort','string');
        $key = $this->request->getPost('key','string');
        $province = $this->request->getPost('province','string');
        $city = $this->request->getPost('city','string');
        $sort= $this->request->getPost('sort','string');
        $order=$this->request->getPost('order','string');
        $all=$this->request->getPost('all','string');


        $builder = $this->modelsManager->createBuilder()
            ->columns('p.iBPPId,p.iCUId,p.tStartTime,p.iChargeId,p.tPlanDate,p.tRealDate,p.mDesc,p.tCreateDate,i.sSchoolName,i.sProvinceName,i.sCityName')
            ->addFrom('Admin\Models\bpm\XHBpmPlan', 'p')
            ->leftJoin('Admin\Models\crm\XhcustInfo', 'i.iCUId=p.iCUId', 'i')
            ->where('p.bDelete=0 and p.bFinish = 0');
        if($tsort==null){
            if($sort&$order){
                $builder->orderBy('i.'.$sort.' '.$order.'');
            }else {
                $builder->orderBy('p.tCreateDate desc');
            }
        }
        if($province&&$province!='--省--'){
            $builder->andWhere('i.sProvinceName=:province:',array('province'=>$province));
        }
        if($city&&$city!='--市--'){
            $builder->andWhere('i.sCityName=:city:',array('city'=>$city));
        }

        if($sNodeName){
            $builder->leftJoin('Admin\Models\bpm\XHBpmPlanContent','p.iBPPId=c.iBPPId ','c')->columns('p.iBPPId,p.iCUId,p.tStartTime,p.iChargeId,p.tPlanDate,p.tRealDate,p.mDesc,p.tCreateDate,p.iCreateUserId,p.tLastModifyDate,p.iLastModifyUserId,i.sSchoolName,i.sProvinceName,i.sCityName,c.tPlanDate as cPlanDate ,c.iType as cType ,c.iBPCId')
                ->andWhere('c.sNodeName=:sNodeName:',array('sNodeName'=>$sNodeName));

            //权限处理部分
            $schools = School::getPower();//获取学校权限
            if (!User::isAdmin() && $schools !== true) {
                $conditionArr = [
                    'conditions' => [],
                    'bind'       => []
                ];
                if (count($schools) > 0) {
                    $conditionArr['conditions'][] = 'i.iSchoolId in ({schools:array})';
                    $conditionArr['bind']  = ['schools' => $schools];
//                            $builder->andWhere('', ['schools' => $schools]);
                }
                $auth = XhcustAuth::find([
                    'columns'    => 'iCUId',
                    'conditions' => 'bDelete=0 AND iAuthId=:iAuthId:',
                    'bind' => array('iAuthId' => Main::getLoginUserInfo('userId'))
                ])->toArray();
                if (count($auth) > 0) {
                    $authCuIds = array_values(array_filter(array_unique(array_column($auth, 'iCUId'))));
                    if ($authCuIds) {
                        $conditionArr['conditions'][] = 'p.iCUId in ({authCUIds:array})';
                        $conditionArr['bind']  = array_merge(['authCUIds' => $authCuIds], $conditionArr['bind']);
                    }
                }
                $conditionArr['conditions'][] = 'i.iCreateUserId = :nowId: ';
                $conditionArr['bind']  =  array_merge(['nowId' => Main::getLoginUserInfo('userId')], $conditionArr['bind']);
                $depArr = User::getExtraPower('dep', 'customer'); //获取客户的部门权限
                if ($depArr) {
                    $userIds = array_values(array_filter(Hrm::getUserByDepId($depArr , true)));
                    if (count($userIds) > 0) {
                        $conditionArr['conditions'][] = 'i.iCreateUserId in ({users:array}) ';
                        $conditionArr['bind']  =  array_merge(['users' => $userIds], $conditionArr['bind']);
                    }
                }
                $conditionArr['conditions'][] = ' p.iChargeId=:iChargeId: OR c.iChargeId=:iChargeId: OR c.sExcuteIds=:iChargeId: ';
                $conditionArr['bind']  =  array_merge(['iChargeId' => Main::getLoginUserInfo('userId')], $conditionArr['bind']);
                $builder->andWhere(implode(' or ', $conditionArr['conditions']), $conditionArr['bind']);
            }

//            $userId=Main::getLoginUserInfo('userId');
//            if(!UserPower::checkUserPower('Bpm_Progress_All')){
//                $builder->andWhere('p.iChargeId=:iChargeId: OR c.iChargeId=:iChargeId:',array('iChargeId'=>$userId));
//            }
            if($startTime==null&&$endTime){
                $startTime='1970-01-01';
            }
            if($endTime==null&&$startTime){
                $endTime=date('Y-m-d',time());
            }
            if($startTime&&$endTime){
                $builder->andWhere('c.tPlanDate>=:startTime:',array('startTime'=>$startTime))->andWhere('c.tPlanDate<=:endTime:',array('endTime'=>$endTime));

            }
            if($type){
//                    $builder->andWhere('c.iType=:iType:',array('iType'=>$type));
                if($type==8){
                    $builder->andWhere('c.iType in ({types:array})',array('types'=>[5,6,7]));
                }else{
                    $builder->andWhere('c.iType=:iType:',array('iType'=>$type));
                }
            }
            if($tsort==2){
                if($sort&&$order){
                    if($sort=="sSchoolName"){
                      //  $sort='sSchoolName';
                        $builder->orderBy('c.tPlanDate DESC'.', i.'.$sort.' '.$order.'');
                    }else{
                        $builder->orderBy('c.tPlanDate DESC'.', p.'.$sort.' '.$order.'');
                    }
                }else{
                    $builder->orderBy('c.tPlanDate DESC');
                }

            }else if($tsort==1){
                if($sort&&$order){
                    if($sort=="sSchoolName"){
                      //  $sort='sSchoolName';
                        $builder->orderBy('c.tPlanDate '.', i.'.$sort.' '.$order.'');
                    }else{
                        $builder->orderBy('c.tPlanDate '.', p.'.$sort.' '.$order.'');
                    }
//                    $builder->orderBy('c.tPlanDate '.',p.'.$sort.' '.$order.'');
                }else{
                    $builder->orderBy('c.tPlanDate ');
                }
            }else{
                if($sort&&$order) {
                    if ($sort == "sSchoolName") {
                       // $sort = 'sSchoolName';
                        $builder->orderBy(' i.' . $sort . ' ' . $order . '');
                    } else {
                        $builder->orderBy(' p.' . $sort . ' ' . $order . '');
                    }
                }else{
                    $builder->orderBy('p.tCreateDate desc');
                }
            }
        }else{
            $newBuilder=$this->modelsManager->createBuilder()
                ->columns('p.iBPPId,p.iCUId,p.tStartTime,p.iChargeId,p.tPlanDate,p.tRealDate,p.mDesc,p.tCreateDate,p.iCreateUserId,p.tLastModifyDate,p.iLastModifyUserId,i.sSchoolName,i.sProvinceName,i.sCityName,u.sSelfPhone')
                ->addFrom('Admin\Models\bpm\XHBpmPlan', 'p')
                ->leftJoin('Admin\Models\crm\XhcustInfo', 'i.iCUId=p.iCUId', 'i')
                ->leftJoin('Admin\Models\user\XhsysUser','p.iChargeId=u.iUserId','u')
                ->where('p.bDelete=0');

            if($province&&$province!='--省--'){
                $newBuilder->andWhere('i.sProvinceName=:province:',array('province'=>$province));
            }
            if($city&&$city!='--市--'){
                $newBuilder->andWhere('i.sCityName=:city:',array('city'=>$city));
            }
            $newBuilder->leftJoin('Admin\Models\bpm\XHBpmPlanContent','p.iBPPId=c.iBPPId ','c')->columns('p.iBPPId,c.iBPCId,c.sNodeName,c.tPlanDate as cPlanDate');
            if($startTime==null&&$endTime){
                $startTime='1970-01-01';
            }
            if($endTime==null&&$startTime){
                $endTime=date('Y-m-d',time());
            }
            if($startTime&&$endTime){
                $newBuilder->andWhere('c.tPlanDate>=:startTime:',array('startTime'=>$startTime))->andWhere('c.tPlanDate<=:endTime:',array('endTime'=>$endTime));

            }

            $schools = School::getPower();//获取学校权限
            if (!User::isAdmin() && $schools !== true) {
                $conditionArr = [
                    'conditions' => [],
                    'bind'       => []
                ];
                if (count($schools) > 0) {
                    $conditionArr['conditions'][] = 'i.iSchoolId in ({schools:array})';
                    $conditionArr['bind']  = ['schools' => $schools];
//                            $builder->andWhere('', ['schools' => $schools]);
                }
                $auth = XhcustAuth::find([
                    'columns'    => 'iCUId',
                    'conditions' => 'bDelete=0 AND iAuthId=:iAuthId:',
                    'bind' => array('iAuthId' => Main::getLoginUserInfo('userId'))
                ])->toArray();
                if (count($auth) > 0) {
                    $authCuIds = array_values(array_filter(array_unique(array_column($auth, 'iCUId'))));
                    if ($authCuIds) {
                        $conditionArr['conditions'][] = 'p.iCUId in ({authCUIds:array})';
                        $conditionArr['bind']  = array_merge(['authCUIds' => $authCuIds], $conditionArr['bind']);
                    }
                }
                $conditionArr['conditions'][] = 'i.iCreateUserId = :nowId: ';
                $conditionArr['bind']  =  array_merge(['nowId' => Main::getLoginUserInfo('userId')], $conditionArr['bind']);
                $depArr = User::getExtraPower('dep', 'customer'); //获取客户的部门权限
                if ($depArr) {
                    $userIds = array_values(array_filter(Hrm::getUserByDepId($depArr , true)));
                    if (count($userIds) > 0) {
                        $conditionArr['conditions'][] = 'i.iCreateUserId in ({users:array}) ';
                        $conditionArr['bind']  =  array_merge(['users' => $userIds], $conditionArr['bind']);
                    }
                }
                $conditionArr['conditions'][] = ' p.iChargeId=:iChargeId: OR c.iChargeId=:iChargeId: OR c.sExcuteIds=:iChargeId: ';
                $conditionArr['bind']  =  array_merge(['iChargeId' => Main::getLoginUserInfo('userId')], $conditionArr['bind']);
                $newBuilder->andWhere(implode(' or ', $conditionArr['conditions']), $conditionArr['bind']);

            }

            if($type){
                if($type==8){
                    $newBuilder->andWhere('c.iType in ({types:array})',array('types'=>[5,6,7]));
                }else{
                    $newBuilder->andWhere('c.iType=:iType:',array('iType'=>$type));
                }
//                $newBuilder->andWhere('c.iType=:iType:',array('iType'=>$type));
            }

//            $userId=Main::getLoginUserInfo('userId');
//            if(!UserPower::checkUserPower('Bpm_Progress_All')){
//                $newBuilder->andWhere('p.iChargeId=:iChargeId: OR c.iChargeId=:iChargeId:',array('iChargeId'=>$userId));
//            }
            $datas=$newBuilder->getQuery()->execute()->toArray();

            if($datas==[]){
                return json_encode($datas);
            }
            $newIds=[];
            $nCIds=[];
            foreach ($datas as $ksdata){ //按需求排序的字段
                $newIds[]=$ksdata['iBPPId'];
                $nCIds[]=$ksdata['iBPCId'];
            }
            $newIds=array_unique($newIds);
            $nCIds=array_unique($nCIds);


            $new=[];
            foreach ($newIds as $id){
                $new[]=$id;
            }

            $newC=[];
            foreach ($nCIds as $id){
                $newC[]=$id;
            }
//

            if($newIds!=null){
                $builder->andWhere('p.iBPPId in ({ids:array})',array('ids'=>$new));
            }
            if($sort&&$order) {
                if ($sort == "sSchoolName") {
                    // $sort = 'sSchoolName';
                    $builder->orderBy(' i.' . $sort . ' ' . $order . '');
                } else {
                    $builder->orderBy(' p.' . $sort . ' ' . $order . '');
                }
            }else{
                $builder->orderBy('p.tCreateDate desc');
            }
        }
        if($key){
            $builder->andWhere('i.sSchoolName Like :key:',array('key'=>'%'.$key.'%'));
        }

        $data=Main::runBuilderPaginator($builder,true);
        if($data['rows']==[]){
            return $this->response->setContent(json_encode($data, JSON_UNESCAPED_UNICODE));
        }
        $ids=[];
        foreach ($data['rows'] as $row){
            $ids[]=$row['iBPPId'];
        }
        $objs=XHBpmPlanContent::find([
            'columns'=>'iBPPId,iBPCId,sNodeName,tPlanDate,tRealDate',
            'conditions'=>'bDelete=0 AND iBPPId in ({ids:array})',
            'bind'=>array('ids'=>$ids),
            'order'=>'iSort,iBPCId',
        ]);
        $items=[];
        foreach ($objs as $obj){
            foreach ($ids as $id){
                if($obj->iBPPId==$id){
                    $items[$obj->iBPPId][]=$obj->toArray();
                }
            }
        }

        foreach ($data['rows'] as $index=>$row){
            $row['progress']='';
            $cCount=0;
            $item=$items[$row['iBPPId']];
            $cCount=count($item);

            $width=(849-$cCount-10)/$cCount;
            foreach ($item as $pContent){
                    $val=$pContent['sNodeName'];
                    $css=$this->getColorType($row['tStartTime'],$pContent['tPlanDate'],$pContent['tRealDate']);
//                    if($order=='asc'&&$sort=='progress'){
//                        $row['progress'].='<div class="progress" style="float: left;border-right:1px solid white "><div class="progress-bar '.$css.'" title="'.$val.'" style="width: '.$width.'px"></div></div>';
//                    }else{
//                        $row['progress'].='<div class="progress" style="float: left;"><div class="progress-bar '.$css.'" title="'.$val.'" style="width: '.$width.'px"></div></div>';
//                    }
                $row['progress'].='<div class="progress" style="float: left;border-right:1px solid white "><div class="progress-bar '.$css.'" title="'.$val.'" style="width: '.$width.'px"></div></div>';

            }
            $data['rows'][$index]=$row;

        }
        return $this->response->setContent(json_encode($data, JSON_UNESCAPED_UNICODE));
    }

    public function financeFormAction(){
        $id=$this->request->getQuery('iBPCId','string');
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::easyUI();
        Assets::importJs('js/myMain.js');
        Assets::datetimePicker();
        Assets::importJs('js/plan/financeForm.js');
        $this->view->pick('plan/financeForm');
        if($id) {
            $obj = XHBpmPlanContent::findFirst([
                'conditions' => 'bDelete=0 AND iBPCId =:id:',
                'bind' => array('id' => $id)
            ]);
            $this->view->setVars([
                'contentInfo' => json_encode($obj->toArray()),
            ]);
        }
    }

    /**
     * 改变节点状态
     * created by dale 2017/9/30
     */
    public function changeNodeStateAction(){
        $id=$this->request->getPost('iBPCId','string') or die('缺少参数');
        $state=$this->request->getPost('iNodeState','string') ;
        $pc=XHBpmPlanContent::findFirst($id);
        $pc->assign($this->request->getPost());
        if($state==1){
            $pc->tRealDate  = date('Y-m-d m:i:s',time());
        }else{
            $pc->tRealDate  = null;
        }
        if($pc->save()){
            return $this->sendSuccessResponse('success');
        }else{
            return $this->sendErrorResponse(500,'error');
        }
    }


    public function getColorType($time1,$time2,$time3){

        if(strtotime($time1)>time()){//未开始,灰色
            return 'gray';
        }else{ //开始
            if($time2==null){  //开始,浅蓝,还未设置预计时间
//                return 'lightblue';
                return 'gray';
            }else {

                if ($time3 == null) {//如果未设定时间
                    if (date('Y-m-d',time()) > $time2) { //延期中
                        $returncss= 'bigRed';
                    } else if(date('Y-m-d',time() + 86400) == $time2){
                        $returncss= 'yellow';
                    }else if(date('Y-m-d',time() + 2*86400) == $time2){
                        $returncss= 'yellow';
                    }else if(date('Y-m-d',time() + 3*86400) == $time2){
                        $returncss= 'yellow';
                    }else{
                        $returncss= 'lightblue';
                    }

                } else {
                    if (strtotime($time3) == strtotime($time2)) { //按时完成
                        $returncss= 'blue';
                    } else if (strtotime($time3) < strtotime($time2)) { //提前完成
                        $returncss= 'green';
                    } else if(date('Y-m-d',time() + 86400) == $time2){
                        $returncss='yellow';
                    }else if(date('Y-m-d',time() + 2*86400) == $time2){
                        $returncss= 'yellow';
                    }else if(date('Y-m-d',time() + 3*86400) == $time2){
                        $returncss= 'yellow';
                    }else{
                        $returncss= 'red';
                    }
                }
                return $returncss;
            }
        }
    }

    public function getType($css){
        switch ($css){
            case  'gray'     : return 1;  //灰色,未开始   background-color: grey;
            case  'lightblue': return 2;  //淡蓝色,开始  background-color: lightskyblue;
            case  'bigRed'   : return 3;  //大红,逾期进行中 background-color: darkred;
            case  'yellow'   : return 4;  //黄色,临近一天 background-color: yellow;
            case  'blue'     : return 5;  //蓝色,正常完成     background-color: #2c6b9f;
            case  'green'    : return 6;  //绿色,提前完成     background-color: green;
            case  'red'      : return 7;  //红色,超期完成     background-color: red;
        }
    }

    public function changeStateAction(){
        $id = $this->request->getPost('id','string') or die('缺少参数');
        $state = $this->request->getPost('state','string') or die('缺少参数');
        $plan=XHBpmPlan::findFirst($id);
        $plan->iState = $state;
        if($plan->save()){
            return $this->response->setContent('success');
        }else{
            return $this->response->setContent('error');
        }
    }

    /**
     * 计划日程
     *
     * created by dale 2017/9/4
     */
    public function planRouteAction(){
        $this->view->pick('plan/planRoute');
        Assets::importJs('js/plan/planRoute.js');
        Assets::easyUI();
        Template::exists('planRoute', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));//检查public/template/from/目录下是否都存在template文件夹
        $listSearchArr = array();
//        $enums['iContent'][''] = '--内容--';
        $enums['date']=[
            'tStartTime'=>'发起时间',
            'tPlanDate'=>'预计完成时间',
            'tRealDate'=>'实际完成时间',
        ];

        $iTPId=XHBpmTemplate::findFirst([
            'columns'=>'iTPId',
            'conditions'=>'bDelete=0',
        ]);
        $iTPId=$iTPId->iTPId;
        $arrs=XHBpmNode::find([
            'columns'=>'iNodeId,sNodeName',
            'conditions'=>'bDelete=0 AND iTPId=:iTPId:',
            'bind'=>['iTPId'=>$iTPId],
            'order'=>'iSort',
        ]);
        $nodes=array_column($arrs->toArray(),'sNodeName','sNodeName');
        $nodes['']='--选择节点内容--';
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_date','data' => $enums['date'] ,'default'=>'1');
        $listSearchArr[] = array('type' => 'text', 'id' => 'List_Search_StartTime','width'=>'100px');
        $listSearchArr[] = array('type' => 'text', 'id' => 'List_Search_EndTime');
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_nodes', 'data' => $nodes, 'default' => '','multiple'=>'true');
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        $listSearchArr[] = array('type' => 'button', 'id' => 'excel_export', 'text' => '导出excel', 'icon' => 'fa fa-file-excel-o');
        // var_dump(Template::createSearchToolBar($listSearchArr, false));die();
        $this->view->setVars(array(
            'List' => Template::createList('List', 'planRoute', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, false),
                'checkbox' => false,
            ]),
        ));
    }


    public function getPlanRouteAction(){
        $dateType = $this->request->getPost('dateType','string');
        $startTime = $this->request->getPost('startTime','string');
        $endTime = $this->request->getPost('endTime','string');
        $key     = $this->request->getPost('key','string');
        $nodes   = $this->request->getPost('nodes');
        $nodes   = array_values(array_filter($nodes));
        $builder=$this->modelsManager->createBuilder()
            ->columns('c.iBPCId, c.iBPPId,c.sNodeName,c.tRealDate,c.tPlanDate, p.iCUId,p.tStartTime,i.sSchoolName,s.sSelfPhone,s.sStaffName')
            ->addFrom('Admin\Models\bpm\XHBpmPlanContent', 'c')
            ->leftJoin('Admin\Models\bpm\XHBpmPlan','p.iBPPId=c.iBPPId' ,'p')
            ->leftJoin('Admin\Models\crm\XhcustInfo', 'i.iCUId=p.iCUId', 'i')
            ->leftJoin('Admin\Models\hrm\XhhrmStaff','c.iChargeId=s.iUserId','s')
            ->where('c.bDelete=0 AND p.bDelete=0');

        if($dateType){
            if($dateType=='tStartTime'){
                $builder->andWhere('p.tStartTime>=:startTime:',array('startTime'=>$startTime))->andWhere('p.tStartTime<=:endTime:',array('endTime'=>$endTime))->orderBy('p.tStartTime ,i.sSchoolName,c.iBPPId,c.iSort');
            }else{
                $builder->andWhere('c.'.$dateType.' >= :startTime:',array('startTime'=>$startTime))
                    ->andWhere('c.'.$dateType.' <= :endTime:',array('endTime'=>$endTime));
                if($dateType=='tPlanDate'){
                  $builder->orderBy('c.tPlanDate ,i.sSchoolName,c.iBPPId,c.iSort');
                }else if($dateType=='tRealDate'){
                    $builder->orderBy('c.tRealDate ,i.sSchoolName,c.iBPPId,c.iSort');
                }
            }
        }

        if($key){
            $builder->andWhere('i.sSchoolName like :key:',array('key'=>'%'.$key.'%'));
        }
        if($nodes!=[]){
            $builder->andWhere('c.sNodeName in ({nodes:array})',array('nodes'=>$nodes));
        }

        $data=Main::runBuilderPaginator($builder,true);

        foreach ($data['rows'] as $index=>$row){
            $data['rows'][$index]['sChargeName']=$row['sStaffName'].'('.$row['sSelfPhone'].')';
        }
        return json_encode($data);
    }
    
    
    
    public function exportPlanRouteAction(){
        $this->view->disable();
        $dateType = $this->request->getQuery('dateType','string');
        $startTime = $this->request->getQuery('startTime','string');
        $endTime = $this->request->getQuery('endTime','string');
        $key     = $this->request->getQuery('key','string');
        $nodes   = $this->request->getQuery('nodes');
        $nodes   = array_values(array_filter(explode(',',$nodes)));
        $builder=$this->modelsManager->createBuilder()
            ->columns('c.iBPCId, c.iBPPId,c.sNodeName,c.tRealDate,c.tPlanDate, p.iCUId,p.tStartTime,i.sSchoolName,s.sSelfPhone,s.sStaffName')
            ->addFrom('Admin\Models\bpm\XHBpmPlanContent', 'c')
            ->leftJoin('Admin\Models\bpm\XHBpmPlan','p.iBPPId=c.iBPPId' ,'p')
            ->leftJoin('Admin\Models\crm\XhcustInfo', 'i.iCUId=p.iCUId', 'i')
            ->leftJoin('Admin\Models\hrm\XhhrmStaff','c.iChargeId=s.iUserId','s')
            ->where('c.bDelete=0 AND p.bDelete=0');

        if($dateType){
            if($dateType=='tStartTime'){
                $builder->andWhere('p.tStartTime>=:startTime:',array('startTime'=>$startTime))->andWhere('p.tStartTime<=:endTime:',array('endTime'=>$endTime))->orderBy('p.tStartTime ,i.sSchoolName,c.iBPPId,c.iSort');
            }else{
                $builder->andWhere('c.'.$dateType.' >= :startTime:',array('startTime'=>$startTime))
                    ->andWhere('c.'.$dateType.' <= :endTime:',array('endTime'=>$endTime));
                if($dateType=='tPlanDate'){
                    $builder->orderBy('c.tPlanDate ,i.sSchoolName,c.iBPPId,c.iSort');
                }else if($dateType=='tRealDate'){
                    $builder->orderBy('c.tRealDate ,i.sSchoolName,c.iBPPId,c.iSort');
                }
            }
        }

        if($key){
            $builder->andWhere('i.sSchoolName like :key:',array('key'=>'%'.$key.'%'));
        }
        if($nodes!=[]){
            $builder->andWhere('c.sNodeName in ({nodes:array})',array('nodes'=>$nodes));
        }

        $scource=$builder->getQuery()->execute()->toArray();

        foreach ($scource as $index=>$row){
            $scource[$index]['sChargeName']=$row['sStaffName'].'('.$row['sSelfPhone'].')';
        }
        if($dateType){
            if($dateType=='tStartTime'){
                $title = [
                    'tStartTime' => '发起时间',
                    'sSchoolName' => '学校名称',
                    'sNodeName' => '节点名称',
                    'tPlanDate' => '预计完成时间',
                    'tRealDate' => '实际完成时间',
                    'sChargeName' => '负责人',
                ];
            }else if($dateType=='tPlanDate'){
                $title = [
                    'tPlanDate' => '预计完成时间',
                    'sSchoolName' => '学校名称',
                    'sNodeName' => '节点名称',
                    'tStartTime' => '发起时间',
                    'tRealDate' => '实际完成时间',
                    'sChargeName' => '负责人',
                ];
                
            }else if($dateType=='tRealDate'){
                $title = [
                    'tRealDate' => '实际完成时间',
                    'sSchoolName' => '学校名称',
                    'sNodeName' => '节点名称',
                    'tStartTime' => '发起时间',
                    'tPlanDate' => '预计完成时间',
                    'sChargeName' => '负责人',
                ];
            }
        }else{
            $title = [
                'tStartTime' => '发起时间',
                'sSchoolName' => '学校名称',
                'sNodeName' => '节点名称',
                'tPlanDate' => '预计完成时间',
                'tRealDate' => '实际完成时间',
                'sChargeName' => '负责人',
            ];
        }
       

        $data = [];
        foreach ($scource as $key => $row) {
            foreach ($title as $filed => $name) {
                $data[$key][$filed] = isset($row[$filed]) ? $row[$filed] : '';
            }
        }
        $fileName = '意向日程' . Main::getLoginUserInfo('userName');
        Tool::exportExcelOnline($fileName, $title, $data);
    }


    
    
    

    public function teachConfirmAction(){
        $iCUId=$this->request->getQuery('iCUId','string');
        Assets::fileInput();
//        if($type==1){
//            Assets::easyUI();
//            $style="#xh_form{
//                        display: none;
//                    }";
//
//        }else if($type==2){
//            $style=".reply{
//                        display: none;
//                     }";
//        }
        Assets::easyUI();
        Assets::importJs('js/myMain.js');
        Assets::importJs('js/plan/teachConfirm.js');
        Assets::importMainJs('assets/xh/xhForm.js');
        $this->view->pick('plan/teachConfirm');
        
        $this->view->setVars([
//            'style'=>$style,
            'iCUId'=>$iCUId,
        ]);
    }


    public function teachListAction(){
        $id=$this->request->getQuery('id','string') or die('缺少参数');
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,"http://zt.yunzuoye.net:82/xh/api/Info/schoolTchBook/".$id);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        //执行并获取HTML文档内容
        $data = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);
        $data=json_decode($data);
        $items=[];
        foreach ($data as $index=>$row){
            $item=[];
            $item['keyId']  = 'T-'.$row->tchId;
            $item['realId'] = $row->tchId;
            $item['name']   = $row->tchName;
            $item['type']   = 1;
            $child=[];
            foreach ($row->books as $key=>$book){
                $child[$key]['keyId']='B-'.$key;
                $child[$key]['realId'] = $key;
                $child[$key]['name']   = $book->bookName;
                $item['type']   = 2;
            }
            $item['children']=$child;
            $item['state']='closed';
            $items[]=$item;
        }

        return $this->sendJsonResponse($items);
    }


    public function getNoticeAction(){
        $time = Main::getConfigByName('bpm');
        $pos = array_search(max($time), $time);
        $maxTime=$time[$pos];
        $startDate=date('Y-m-d',time()+86400);
        $maxEndDate=date('Y-m-d',time()+$maxTime*86400);
        $userId=Main::getLoginUserInfo('userId');
        $builder = $this->modelsManager->createBuilder()  //获取按预计完成日期排序的,负责人或执行部门负责人是UserId的记录
                ->columns('i.sSchoolName,c.iBPCId,c.sNodeName,c.bNotify,c.sOtherPhone,c.iChargeId,c.sExcuteIds,c.tPlanDate,c.tRealDate,p.iCUId')
                ->addFrom('Admin\Models\bpm\XHBpmPlanContent','c')
                ->leftJoin('Admin\Models\bpm\XHBpmPlan','c.iBPPId=p.iBPPId','p')
                ->leftJoin('Admin\Models\crm\XhcustInfo','i.iCUId=p.iCUId','i')
                ->andWhere('c.bDelete=0 AND (c.tPlanDate>=:startDate: AND c.tPlanDate<=:maxEndDate:) AND c.bNotify=1 ',array('startDate'=>$startDate,'maxEndDate'=>$maxEndDate))
                ->orderBy('c.tPlanDate')
                ->andWhere('c.iChargeId=:userId:',array('userId'=>$userId));
        $data=$builder->getQuery()->execute()->toArray();
        if($data==[]){
            return $this->sendJsonResponse(['data'=>[],'total'=>0,'config'=>[]]);
        }
        $notice=[];
        $baseUrl=$this->di->getShared('url')->getBaseUri();
        $serverUrl=$_SERVER['HTTP_HOST'];
        foreach ($data as $index=>$row){
            $daynum=intval((strtotime($row['tPlanDate'])-time())/86400)+1;//距离当前日期的天数
            $flag=false;
//            if($daynum<=$time['excuteDate']&&$row['sExcuteIds']==$userId){  //日期小于执行日期
//                $flag=true;
//            }
            if($daynum<=$time['chargeDate']&&$row['iChargeId']==$userId){
                $flag=true;
            }
            if($flag){
                $item=[];
                $item['msg']="{$row['sSchoolName']} {$row['sNodeName']} 预计 {$row['tPlanDate']} 完成，距离完成时间还有{$daynum}天";
                $item['url']=$serverUrl.$baseUrl.'bpm/plan/contentForm?id='.$row['iBPCId'];
                $item['title']='编辑'.$row['sNodeName'];
                $notice['data'][]=$item;
            }

        }
        $total=count($notice['data']);
        
        $notice['total']=$total;
        $notice['config']['size']='lg';
        $notice['config']['button']='提交';
        $notice['config']['backClose']=false;
        $notice['config']['style']="width: 100%;;border-style: none;padding: 0px;height: 360px";
        return $this->sendJsonResponse($notice);
    }


    /**
     * 根据id获取电话
     *
     * @param $userId
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by dale 20180361
     */
    public function getPhoneAction($userId){
        $obj = XhhrmStaff::findFirst([
            'columns'    => 'sSelfPhone',
            'conditions' => 'bDelete = 0  AND iUserId = :iUserId:',
            'bind'       => ['iUserId' => $userId],
        ]);
        return $this->sendJsonResponse(['phone' =>$obj->sSelfPhone]);
    }

    /**
     * 验证是否已经填写完整
     *
     * @param $tran
     * @return bool
     * create by dale 20180302
     */
    public function transCheck($tran){
        $bool1 = false;
        $bool2 = false;
        $bool3 = false;
        $bool5 = false;
        if($tran['bVerify'] == 1  && isset($tran['tVerifyDate']) && $tran['tVerifyDate'] != '' ){
            $bool1 = true;
        }else if($tran['bVerify'] == 0 ){
            $bool1 = true;
        }
        if(isset($tran['iOfficeNum']) && $tran['iOfficeNum'] > 0 && $tran['sOfficeAddress'] != ''){
            $bool2 = true;
        }else if(isset($tran['iOfficeNum']) && $tran['iOfficeNum'] == 0){
            $bool2 = true;
        }

        if(isset($tran['iOtherNum']) && $tran['iOtherNum'] > 0 && $tran['mOtherAddress'] != ''){
            $bool3 = true;
        }else if(isset($tran['iOtherNum']) && $tran['iOtherNum'] == 0){
            $bool3 = true;
        }
//        if(!$tran['bKnow'] && $tran['bKnow']!=0){
//            $bool5 = true;
//        }
        $config = ['sSchChargeName','iStudentNum','iTeacherNum','sYear', 'iClassNum',
                   'sClasses','tParentTrain','tStuTrain','tTechInTrain','tTechOpTrain',
                   'sSchChargeName','sSchChargePhone','tRunItemDate','Retian1','sSchNetChargeName'
                    ,'sSchNetChargePhone','tNetTestDate','iTchRoom'];
        $bool4 = true;
        foreach ($config as $val){
            if(!$tran[$val]){
                return false;
            }
        }
//        var_dump([$bool1,$bool2,$bool3,$bool4]);die;
        return $bool1 && $bool2 && $bool3 && $bool4 ;
    }


    /**
     * 获取商品信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180403
     */
    public function getProdAction(){
//        $sql  = "select p.iProdId,p.iTypeId,p.sMeasures,p.sProdName,t.sTypeName from  XHIms_Product as p,XHIms_ProdType as t  WHERE  p.iTypeId = t.iTypeId AND t.sTypeName = '充电设备' ";
        $sql = "select  p.iProdId,p.iPTId,p.sMeasure,p.sProdName,t.sType from XHIms_Produce as p,XHIms_ProduceType as t where  p.iPTId  = t.iPTId AND t.sType = '充电设备'";
        $data = $this->db->fetchAll($sql);
        return $this->sendJsonResponse($data);
    }

    /**
     * 完成计划
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180404
     */
    public function finishPlanAction(){
        $id = $this->request->getPost('id');
        if(!$id){
            return $this->sendErrorResponse(400,'缺少参数');
        }
        $plan = XHBpmPlan::findFirst($id);
        $plan->bFinish = 1;
        $heightDate = $this->getHeightTime($plan->iBPPId);
        $plan->tRealDate = $heightDate ?: date('Y-m-d',time());
        if(!$plan->save()){
            return $this->sendErrorResponse(500,'保存失败');
        }
        return $this->sendSuccessResponse('保存成功');

    }

    /**
     * 流程计划电箱出库
     *
     * @param $data
     * @param $schoolId
     * @param $iBPCId
     *
     * @return bool
     * create by dale 20180403
     */
    public function outPlan($data,$schoolId,$iBPCId){
        foreach ($data as $row) { //出库记录保存
            if ($row['outNum'] > 0) {
                $num = $data['outNum'];
                if($row['iPOutId']){
                    $box = XHImsProduceOut::findFirst($row['iPOutId']);
                    $num = $box->iOutNum - $num;
                }else{
                    $box = new XHImsProduceOut();
                }
                $box->iProdId    = $row['iProdId'];
                $box->iOutNum    = $row['outNum'];
                $box->iSchoolId  = $schoolId;
                $box->iOutType   = 3;
                $box->iOutTypeId = $iBPCId;
                if (!$box->save()) {
                    return false;
                }
//                $prod = XHImsProduce::findFirst($box->iProdId);
//                $prod->iCurrentNum = $prod->iCurrentNum + $num;
//                if (!$prod->save()){
//                    return false;
//                }
                Ims::uploadData($box->iProdId);
            } else if (intval($row['outNum']) === 0  && $row['iPOutId']) {
                $box = XHImsProduceOut::findFirst($row['iPOutId']);
                $box->bDelete = 1;
                if (!$box->save()) {
                    return false;
                }
                Ims::uploadData($box->iProdId);
//                $prod = XHImsProduce::findFirst($box->iProdId);
//                $prod->iCurrentNum = $prod->iCurrentNum - $box->iOutNum;
//                if (!$prod->save()){
//                    return false;
//                }
            }
        }
        return true;
    }

    /**
     * 平板计划
     *
     * create by xjq 20180528
     */
    public function planTabletAction(){
        $schoolId = $this->request->getQuery('schoolId' , 'int' );
        $this->view->pick('plan/planTablet');
        Assets::select2();
        Assets::importJs('js/plan/planTablet.js');
        $classList = XhsysUser::find([
            'columns'    => 'sAdClsName as className',
            'conditions' => 'iSchoolId = :schoolId: and bHistory = 0 and bDisable = 0 and bDelete = 0 and iUserType = 1 ',
            'bind'       => ['schoolId' => $schoolId],
            'group'      => 'sAdClsName'
        ])->toArray();
        $classes = array_column($classList , 'className');
        $teachers = XhsysUser::find([
            'columns'    => 'iUserId,sUserName',
            'conditions' => 'bDelete = 0 and  iSchoolId = :iSchoolId: and iUserType = 4 and  bDisable = 0 and bHistory = 0 ',
            'bind'       => ['iSchoolId' => $schoolId],
        ])->toArray();
        $teachers = array_column($teachers , 'sUserName' , 'iUserId');
        $this->view->setVars([
            'classes'  => $classes,
            'teachers' => $teachers,
            'schoolId' => $this->request->getQuery('schoolId','int'),
            'bpId'     => $this->request->getQuery('iBPPId' , 'int')
        ]);
    }





    /**
     * 获取学生数量
     *
     * @return string
     * create by xjq 20180528
     */
    public function getStuNumAction(){
        $schoolId = $this->request->getPost('schoolId' , 'int');
        $classes  = $this->request->getPost('classes');
        $sql = "select count(iUserId) as num , sAdClsName from XHSys_User where iSchoolId = {$schoolId} and bDelete = 0 and iUserType = 1 and iUserId not in (select iUserId from XHSys_AccountDeviceLocked where bDelete = 0 and iUserId is not null ) and bHistory = 0 and bDisable = 0 group by  sAdClsName";
        $data = $this->db->fetchAll($sql);
        $data = array_column($data , 'num' , 'sAdClsName');
        $num = 0;
        foreach ($classes as $class) {
            $num += isset($data[$class]) ? $data[$class] : 0 ;
        }
        return $this->sendJsonResponse(['total' => $num ,'data' => $data]);
    }


    /**
     * 获取教师数量
     *
     * @return string
     *
     * create by xjq 20180529
     */
    public function getTchNumAction(){
        $teachers  = $this->request->getPost('teachers');
        $sql = " select iUserId from XHSys_AccountDeviceLocked  where iUserId in (" . implode(',' , $teachers) . ") and bDelete = 0 ";
        $data = $this->db->fetchAll($sql);
        $data = array_column($data , 'iUserId'); //已绑定的Id
        foreach ($teachers as $index => $userId) {
            if (in_array($userId , $data)) {
                unset($teachers[$index]);
            }
        }
        $teachers = array_values($teachers);
        return $this->sendJsonResponse(['total' => count($teachers) , 'data' => $teachers]);
    }

    /**
     * 获取学生json
     *
     * @param $classes
     * @param $schoolId
     * @return array
     * create by xjq 20180528
     */
    public function getStuJson($classes , $schoolId){
        $sql = "select iUserId,sAdClsName from XHSys_User where iSchoolId = {$schoolId} and bDelete = 0 and iUserType = 1 and iUserId not in (select iUserId from XHSys_AccountDeviceLocked  where bDelete = 0 and iUserId is not null ) and sAdClsName in ('" . implode("','",$classes) . "')  and bHistory = 0 and bDisable = 0 order by  sAdClsName";
        $data = $this->db->fetchAll($sql);
        $arr = [];
        foreach ($data as $index => $row) {
            $arr[$row['sAdClsName']][] = $row['iUserId'];
        }
        return $arr;
    }

    /**
     * 获取真实的老师
     *
     * @param $teachers
     * @return null|string
     *
     * create by xjq 20180529
     */
    public function getRealTch($teachers){
        if (count($teachers) <= 0) {
            return null;
        }
        $sql = " select iUserId from XHSys_AccountDeviceLocked  where iUserId in (" . implode(',' , $teachers) . ") ";
        $data = $this->db->fetchAll($sql);
        $data = array_column($data , 'iUserId'); //已绑定的Id
        foreach ($teachers as $index => $userId) {
            if (in_array($userId, $data)) {
                unset($teachers[$index]);
            }
        }
        $teachers = array_values($teachers);
        if (count($teachers) <= 0 ) {
            return null;
        }
        return implode(',' , $teachers);
    }

    /**
     * 保存申请
     *
     * create by xjq 20180529
     * modify by dale 20181114  添加关闭平板领用
     */
    public function saveApplyAction(){
        try{
            $postData = $this->request->getPost();
            if (count($postData['classes']) <= 0 ) {
               return $this->sendErrorResponse(400 , '缺少参数');
            }
            if (!$postData['stuTabletNum'] && !$postData['tchTabletNum']){
                return $this->sendErrorResponse(400 , '申请的领用数目不能为零');
            }
            $checkClose = XHBpmPlan::findFirst($postData['iBPPId']);
            if (!$checkClose) {
                return $this->sendErrorResponse(400, '未找到流程计划');
            }
            if ($checkClose->bApplyTab != 1) {
                return $this->sendErrorResponse(400, '该流程计划已经关闭平板领用');
            }
            if ($postData['iRTId']) {
                $obj = XHImsApplyTablet::findFirst($postData['iRTId']);
            }else{
                if (!$this->checkEnable($postData['iBPPId'])) {
                    return $this->sendErrorResponse(400 , '该流程计划已有平板申请还未完结');
                }
                $obj = new  XHImsApplyTablet();
            }
            $teachers = $postData['teachers'];
            if (count($teachers) != $postData['tchTabletNum']) {
                return $this->sendErrorResponse(400 , '教师数目与实际选中教师数目不符');
            }
            $obj->iSchoolId = $postData['iSchoolId'];
            $obj->iBPPId    = $postData['iBPPId'];
            $obj->iStuNum   = $postData['stuTabletNum'];
            $obj->iTchNum   = $postData['tchTabletNum'];
            $obj->sClasses  = implode(',' , $postData['classes']);
            $obj->sTeachers = implode(',' , $postData['teachers']);
            $obj->mStuJson  = $this->getStuJson($postData['classes'] , $postData['iSchoolId']);
            $obj->sRealTch  = $this->getRealTch($postData['teachers']);
            if (!$obj->save()) {
                return $this->sendErrorResponse(500 , '保存失败');
            }
            try {
                $phones = Main::getConfigByName('ims')['ReceiveSendPhones'];
                if ($phones) {
                    $phones = explode(',', $phones);
                }
                $schoolName = XhschoolInfo::getSchoolArray()[$obj->iSchoolId];
                $names = '';
                if ($postData['teachers']) {
                    $names = XhsysUser::getUserNameById($postData['teachers']);
                    $names = implode(',', array_values($names));
                }
                foreach ($phones as $phone){
                    $phone = trim($phone);
                    Main::sendSMS($phone, "{$schoolName}的平板申领,班级：{$obj->sClasses},教师：{$names},预计学生平板数目：{$obj->iStuNum},预计教师平板数目:{$obj->iTchNum}");
                }
            } catch (\Exception $e) {

            } finally {
//                if ($postData['iBPPId']) {
//                    $transObj = XHBpmTransList::findFirst([
//                        'conditions' => 'iBPPId = :iBPPId: and bDelete = 0',
//                        'bind'       => ['iBPPId' => $postData['iBPPId']]
//                    ]);
//                    if ($transObj) {
//                        $transObj->bUpdate = 1;
//                        if (!$transObj->save()) {
//                            return $this->sendErrorResponse(400, '保存失败');
//                        }
//                    }
//                }
                return $this->sendSuccessResponse('保存成功');
            }

//            Queue::put('sendApplyPhone',['phones' => $obj->toArray(),'msg' => "{$schoolName}的平板申领,班级：{$content['obj']['sClasses']},教师：{$names},预计学生平板数目：{$content['obj']['iStuNum']},预计教师平板数目:{$content['obj']['iTchNum']}"]);

        }catch ( \Exception $e){
            return $this->sendErrorResponse(500 , $e->getMessage());
        }
    }

    /**
     * 流程计划
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181011
     */
//    public function copyOldDataAction(){
//        try {
//            $objArr = XHBpmTransList::find([
//                'conditions' => 'bDelete = 0'
//            ]);
//            $this->db->begin();
//            foreach ($objArr as $obj) {
//                $arr = [];
//                $arr['sClasses'] = $obj->sClasses;
//                $arr['stuNum'] = $obj->iStudentNum;
//                $arr['tchNum'] = $obj->iTeacherNum;
//                $arr['classNum'] = $obj->iClassNum;
//                $obj->mOldData = json_encode($arr, JSON_UNESCAPED_UNICODE);
//                if (!$obj->save()) {
//                    throw new \Exception('旧数据保存失败');
//                }
//            }
//            $this->db->commit();
//            return $this->sendSuccessResponse('保存成功');
//        } catch (\Exception $e) {
//            return $this->sendErrorResponse(
//                500,
//                $e->getMessage(),
//                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
//            );
//        }
//    }

    /**
     * 清空流转单
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181015
     */
//    public function emptyTransListAction() {
//        try {
//            $objArr = XHBpmTransList::find([
//                'conditions' => 'bDelete = 0 and bUpdate = 1'
//            ]);
//            $this->db->begin();
//            foreach ($objArr as $obj) {
//                $obj->iStudentNum = 0;
//                $obj->iTeacherNum = 0;
//                $obj->iClassNum   = 0;
//                $obj->sClasses    = '';
//                if (!$obj->save()) {
//                    throw new XhException('保存失败');
//                }
//            }
//            $this->db->commit();
//            return $this->sendSuccessResponse('清空成功');
//        } catch (\Exception $e) {
//            $this->db->rollback();
//            return $this->sendErrorResponse(
//                500,
//                $e->getMessage(),
//                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
//            );
//        }
//    }

    /**
     * 回复未更新的数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181015
     */
//    public function reserveTransListAction(){
//        try {
//            $objArr = XHBpmTransList::find([
//                'conditions' => 'bDelete = 0 and bUpdate = 0',
//            ]);
//            $this->db->begin();
//            foreach ($objArr as $obj) {
//                $oldData = json_decode($obj->mOldData, true);
//                $obj->iStudentNum = $oldData['stuNum'];
//                $obj->iTeacherNum = $oldData['tchNum'];
//                $obj->iClassNum   = $oldData['classNum'];
//                $obj->sClasses    = $oldData['sClasses'];
//                if (!$obj->save()) {
//                    throw new XhException('保存失败');
//                }
//            }
//            $this->db->commit();
//            return $this->sendSuccessResponse('未锁定的数据回复成功');
//        } catch (\Exception $e) {
//            return $this->sendErrorResponse(
//                500,
//                $e->getMessage(),
//                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
//            );
//        }
//    }

    /**
     * 锁定数据恢复
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181217
     */
    public function reserveTransListAction()
    {
        try {
            $objArr = XHBpmTransList::find([
                'conditions' => 'bDelete = 0 and bUpdate = 1',
            ]);
            $this->db->begin();
            foreach ($objArr as $obj) {
                if ($obj->mOldData) {
                    $oldData = json_decode($obj->mOldData, true);
                    if (array_key_exists('stuNum', $oldData)) {
                        $obj->iStudentNum = Tool::getValue($oldData, 'stuNum', 0);
                        $obj->iTeacherNum = Tool::getValue($oldData, 'tchNum', 0);;
                        $obj->iClassNum   = Tool::getValue($oldData, 'classNum', 0);
                        $obj->sClasses    = Tool::getValue($oldData, 'sClasses', 0);
                        if (!$obj->save()) {
                            throw new XhException('保存失败');
                        }
                    }
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('锁定的数据回复成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }


    /**
     * 更新流转单
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181010
     */
//    public function updateTransListAction()
//    {
//        try {
//            $applyArr = XHImsApplyTablet::find([
//                'columns'    => 'sClasses,iStuNum,iTchNum,iBPPId,iSchoolId',
//                'conditions' => 'iType = 1 and iState = 3 and bDelete = 0 ',
//                'order'      => 'iBPPId',
//            ])->toArray();
//            $groupArr = [];
//            foreach ($applyArr as $apply) {
//                $groupArr[$apply['iBPPId']][] = $apply;
//            }
//            $combineArr = [];
//            foreach ($groupArr as $iBPPId => $group) {
//                $combineArr[$iBPPId] = ['iStuNum'=> 0, 'iTchNum' => 0, 'sClasses' => ''];
//                foreach ($group as $item) {
//                    if ($item['iStuNum']) {
//                        $combineArr[$iBPPId]['iStuNum'] += $item['iStuNum'];
//                    }
//                    if ($item['iTchNum']) {
//                        $combineArr[$iBPPId]['iTchNum'] += $item['iTchNum'];
//                    }
//                    $oldClassArr = array_values(array_filter(explode(',', $combineArr[$iBPPId]['sClasses'])));
//                    $newClassArr = array_values(array_filter(explode(',', $item['sClasses'])));
//                    $mergeArr = array_values(array_filter(array_unique(array_merge($oldClassArr, $newClassArr))));
//                    $combineArr[$iBPPId]['sClasses'] = implode(',', $mergeArr);
//                }
//            }
//            $objArr = XHBpmTransList::find([
//                'conditions' => 'bDelete = 0 and iBPPId in ({ids:array})',
//                'bind'       => ['ids' => array_keys($combineArr)]
//            ]);
//            $this->db->begin();
//            foreach ($objArr as $obj) {
//                if (isset($combineArr[$obj->iBPPId])) {
//                    $obj->iStudentNum = $combineArr[$obj->iBPPId]['iStuNum'];
//                    $obj->iTeacherNum = $combineArr[$obj->iBPPId]['iTchNum'];
//                    $obj->iClassNum   = count(explode(',', $combineArr[$obj->iBPPId]['sClasses']));
//                    $obj->sClasses    = $combineArr[$obj->iBPPId]['sClasses'];
//                    $obj->bUpdate = 1;
//                    if(!$obj->save()) {
//                        $this->db->rollback();
//                        return $this->sendErrorResponse(500, '保存失败');
//                    }
//                }
//            }
//            $this->db->commit();
//            return $this->sendSuccessResponse('保存成功');
//        } catch (\Exception $e) {
//            return $this->sendErrorResponse(
//                500,
//                $e->getMessage(),
//                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
//            );
//        }
//    }

    /**
     * 更新学生列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181010
     */
//    public function updateStuTransListAction()
//    {
//        try {
//            $tabletArr = XHImsApplyTablet::find([
//                'columns'    => 'iRTId,iStuNum,sStudents,iSchoolId,tCreateDate',
//                'conditions' => 'bDelete = 0 and iState = 3 and iType = 2',
//            ])->toArray();
//            $this->db->begin();
//            foreach ($tabletArr as $tablet) {
//                if ($tablet["iSchoolId"]) {
//                    $sql = " select p.iBPPId,c.iSchoolId from XHBpm_Plan as p left join XHCust_Info as c on p.iCUId = c.iCUId
//                    where p.bDelete = 0 and p.tCreateDate < '{$tablet["tCreateDate"]}'
//                    and c.iSchoolId = {$tablet["iSchoolId"]} order by p.tCreateDate desc ";
//                    $data = $this->db->fetchOne($sql);
//                    if ($data) {
//                        $iBBPId = Tool::getValue($data, 'iBPPId', null);
//                        if ($iBBPId) {
//                            if ($tablet['iRTId']) {
//                                $this->db->execute("update XHIms_ApplyTablet set iBPPId = {$iBBPId} where iRTId = {$tablet['iRTId']} ");
//                            }
//                            $obj = XHBpmTransList::findFirst([
//                                'conditions' => 'bDelete = 0 and iBPPId = :iBPPId:',
//                                'bind'       => ['iBPPId' => $iBBPId]
//                            ]);
//                            if ($obj) {
//                                if(!$obj->iStudentNum) {
//                                    $obj->iStudentNum = 0;
//                                }
//                                if ($tablet['iStuNum']) {
//                                    $obj->iStudentNum += $tablet['iStuNum'];
//                                    $obj->bUpdate = 1;
//                                    if ($tablet['sStudents']) {
//                                        $classSql = "select sAdClsName from XHSys_User where iUserId in ({$tablet['sStudents']})
//                                  group by sAdClsName ";
////                                    var_dump($classSql);die;
//                                        $classes = array_column($this->db->fetchAll($classSql), 'sAdClsName');
//                                        if ($classes) {
//                                            $oldClass = explode(',', $obj->sClasses);
//                                            if (!$oldClass) {
//                                                $oldClass = [];
//                                            }
//                                            $newClass = array_values(array_filter(array_unique(array_merge($oldClass, $classes))));
//                                            $obj->sClasses = implode(',', $newClass);
//                                        }
//                                    }
//
//                                    if (!$obj->save()) {
//                                        $this->db->rollback();
//                                        return $this->sendErrorResponse('保存失败');
//                                    }
//                                }
//
//                            }
//
//                        }
//                    }
//                }
//            }
//            $this->db->commit();
//            return $this->sendSuccessResponse('保存成功');
//        } catch (\Exception $e) {
//            $this->db->rollback();
//            return $this->sendErrorResponse(
//                500,
//                $e->getMessage(),
//                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
//            );
//        }
//    }


    /**
     * 更新教师流转单
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181010
     */
//    public function updateTchTransListAction()
//    {
//        try {
//            $tabletArr = XHImsApplyTablet::find([
//                'columns'    => 'iRTId,iTchNum,iSchoolId,tCreateDate',
//                'conditions' => 'bDelete = 0 and iState = 3 and iType = 3',
//            ])->toArray();
//            $this->db->begin();
//            foreach ($tabletArr as $tablet) {
//                if ($tablet["iSchoolId"]) {
//                    $sql = " select p.iBPPId,c.iSchoolId from XHBpm_Plan as p left join XHCust_Info as c on p.iCUId = c.iCUId
//                    where p.bDelete = 0 and p.tCreateDate < '{$tablet["tCreateDate"]}'
//                    and c.iSchoolId = {$tablet["iSchoolId"]} order by p.tCreateDate desc ";
//                    $data = $this->db->fetchOne($sql);
//                    if ($data) {
//                        $iBBPId = Tool::getValue($data, 'iBPPId', null);
//                        if ($iBBPId) {
//                            if ($tablet['iRTId']) {
//                                $this->db->execute("update XHIms_ApplyTablet set iBPPId = {$iBBPId} where iRTId = {$tablet['iRTId']} ");
//                            }
//                            $obj = XHBpmTransList::findFirst([
//                                'conditions' => 'bDelete = 0 and iBPPId = :iBPPId:',
//                                'bind'       => ['iBPPId' => $iBBPId]
//                            ]);
//                            if ($obj) {
//                                if(!$obj->iTeacherNum) {
//                                    $obj->iTeacherNum = 0;
//                                }
//                                $obj->bUpdate = 1;
//                                if ($tablet['iTchNum']) {
//                                    $obj->iTeacherNum += $tablet['iTchNum'];
//                                    if (!$obj->save()) {
//                                        $this->db->rollback();
//                                        return $this->sendErrorResponse('保存失败');
//                                    }
//                                }
//                            }
//
//                        }
//                    }
//                }
//            }
//            $this->db->commit();
//            return $this->sendSuccessResponse('保存成功');
//        } catch (\Exception $e) {
//            $this->db->rollback();
//            return $this->sendErrorResponse(
//                500,
//                $e->getMessage(),
//                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
//            );
//        }
//    }




    /**
     * 设置是否可以使用
     *
     * @param $iBPPId
     * @return bool
     *
     * create by xjq 20180529
     */
    public function checkEnable($iBPPId){
        $res = XHImsApplyTablet::findFirst([
            'conditions' => 'bDelete = 0 and iBPPId = :iBPPId: and iType = 1 and iState != 3 ',
            'bind'       => ['iBPPId' => $iBPPId],
        ]);
        return $res ? false : true;
    }

    /**
     * 开启关闭平板领用
     *
     * @param string $type
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181114
     */
    public function closePlanApplyTabAction($type = 'close')
    {
        try {
            $iBPPId = $this->request->getPost('iBBPId', 'string');
            if (!in_array($type, ['open', 'close'])) {
                return $this->sendErrorResponse(400, '未知类型');
            }
            if (!$iBPPId) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $plan = XHBpmPlan::findFirst($iBPPId);
            if (!$plan) {
                return $this->sendErrorResponse(400, '未找到记录');
            }
            if ($type == 'close') {
                if ($plan->bApplyTab == 0) {
                    return $this->sendErrorResponse(400, '该流程已关闭平板申领');
                }
                $plan->bApplyTab = 0;
                if (!$plan->save()) {
                    return $this->sendErrorResponse(500, '保存失败');
                }
                return $this->sendSuccessResponse('关闭平板申领成功');
            } else if ($type == 'open') {
                if ($plan->bApplyTab == 1) {
                    return $this->sendErrorResponse(400, '该流程已开启平板申领');
                }
                $plan->bApplyTab = 1;
                if (!$plan->save()) {
                    return $this->sendErrorResponse(500, '保存失败');
                }
                return $this->sendSuccessResponse('开启平板申领成功');
            } else {
                return $this->sendErrorResponse(500, '未知类型');
            }
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    public  static  $planReceiveState = [1 => '待确认' , 2 => '待领用', 3 => '已领用'];
    public static  $planReceiveType = [1 => '流程计划' , 2 => '学生机', 3 => '教师机', 4 =>'备用机', 5 => '公用机' , 6 => '自用机' ];
    public static $tabReturnSource = [1 => '设备领用', 2 => '学生管理', 3 =>'教师管理'];
    public static $tabReturnState   = [1 => '待确认' , 2 => '待归还', 3 => '已归还'];

    /**
     * 获取平板出入详细
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by dale  20181206
     */
    public function planTabletDetailAction()
    {
        try {
            $iBPPId = $this->request->getQuery('iBPPId');
            if (!$iBPPId) {
                return $this->sendViewError('缺少参数');
            }
            $this->view->pick('plan/planTabletDetail');
            Assets::easyUI('', true);
            Assets::importJs('js/plan/planTabletDetail.js');
            if ($iBPPId) {
                $applyTabArr = XHImsApplyTablet::find([
                    'conditions' => 'bDelete = 0 and iBPPId = :iBPPId:',
                    'bind'       => ['iBPPId' => $iBPPId],
                ])->toArray();
                $retTabArr = XHImsReturnTab::find([
                    'conditions' => 'bDelete = 0 and iBPPId = :iBPPId:',
                    'bind'       => ['iBPPId' => $iBPPId],
                ])->toArray();
                $applyInfo = [
                    'realClass' => '',
                    'realClassNum' => 0,
                    'realTchNum' => 0,
                    'realStuNum' => 0
                ];
                if ($applyTabArr) {
                    $classArr = [];
                    foreach ($applyTabArr as $applyTab) {
                        if ($applyTab['iState'] != 3) {
                            continue;
                        }
                        if ($applyTab['iType'] == 1) {
                            $applyInfo['realStuNum'] += Tool::getValue($applyTab, 'iStuNum', 0);
                            $applyInfo['realTchNum'] += Tool::getValue($applyTab, 'iTchNum', 0);
                            $class = Tool::getValue($applyTab, 'sClasses', '');
                            if ($class) {
                                $class = explode(',', $class);
                                $classArr = array_merge($classArr, $class);
                            }
                        } elseif ($applyTab['iType'] == 2) {
                            $applyInfo['realStuNum'] += Tool::getValue($applyTab, 'iStuNum', 0);
                            $classSql = "select sAdClsName from XHSys_User where iUserId in ({$applyTab['sStudents']})
                                  group by sAdClsName ";
                            $class = $this->db->fetchAll($classSql);
                            if ($class) {
                                $class = array_column($class, 'sAdClsName');
                                if ($class) {
                                    $classArr = array_merge($classArr, $class);
                                }
                            }
                        } elseif ($applyTab['iType'] == 3) {
                            $applyInfo['realTchNum'] += Tool::getValue($applyTab, 'iTchNum', 0);
                        }
                    }
                    $classArr = array_values(array_unique(array_filter($classArr)));
                    $applyInfo['realClass'] = implode(',', $classArr);
                    $applyInfo['realClassNum'] = count($classArr);
                }

                if ($retTabArr) {
                    foreach ($retTabArr as $retTab) {
                        if ($retTab['iState'] != 3) {
                            continue;
                        }
                        if (!is_array($retTab['mData'])) {
                            $retTab['mData'] = $retTab['mData'] ? unserialize($retTab['mData']) : [];
                        }
                        if ($retTab['iSource'] == 1) { //设备申领
                            foreach ($retTab['mData'] as $row) {
                                $devType = Tool::getValue($row, 'iReceivePurpose', '');
                                if ($devType &&  $devType == '教师机') {
                                    $applyInfo['realTchNum'] -= 1;
                                }
                            }
//                        $applyInfo['realStuNum'] += Tool::getValue($applyTab, 'iStuNum', 0);
//                        $applyInfo['realTchNum'] += Tool::getValue($applyTab, 'iTchNum', 0);
//                        $class = Tool::getValue($applyTab, 'sClasses', '');
//                        if ($class) {
//                            $class = explode(',', $class);
//                            $classArr = array_merge($classArr, $class);
//                        }
                        } elseif ($retTab['iSource'] == 2) { //学生列表
                            $applyInfo['realStuNum'] -= count($retTab['mData']);
                        } elseif ($retTab['iSource'] == 3) { //教师列表
                            $applyInfo['realTchNum'] -= count($retTab['mData']);
                        }
                    }
                }
                $this->view->setVar('applyInfo', $applyInfo);
            }

            $listSearchArr1 = $listSearchArr2 = [];
            $listSearchArr1[] = array('type' => 'select', 'id' => 'select_state', 'data' => array_merge([0 => '状态'], self::$planReceiveState), 'default' => 0, 'style' => 'width:100px;' );
            $listSearchArr1[] = array('type' => 'select', 'id' => 'select_type', 'data' => array_merge([0 => '类型'], self::$planReceiveType), 'default' => 0, 'style' => 'width:100px;' );
            $listSearchArr1[] = array('type' => 'text', 'id' => 'list_search1', 'label' => ' 搜索： ');
            $listSearchArr1[] = array('type' => 'button', 'id' => 'bt_list_search1', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');


            $listSearchArr2[] = array('type' => 'select', 'id' => 'select_source',
                'data' => array_merge([0 => '——来源——'], self::$tabReturnSource), 'default' => 0, 'style' => 'width:100px;');
            $listSearchArr2[] = array('type' => 'select', 'id' => 'select_states',
                'data' => array_merge([0 => '归还状态'], self::$tabReturnState), 'default' => 0, 'style' => 'width:100px;');
            $listSearchArr2[] = array('type' => 'text', 'id' => 'list_search2', 'label' => ' 搜索： ','style' => 'width:100px !important;');
            $listSearchArr2[] = array('type' => 'button', 'id' => 'bt_list_search2', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');

            return $this->view->setVars([
                'iBPPId' => $iBPPId,
                'leftList'       => Template::createList('leftList', 'Device_TabReceive', [
                    'searchToolbar' => Template::createSearchToolBar($listSearchArr1, false),
//                    'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
                ]),
                'rightList'       => Template::createList('rightList', 'Device_TabReturn', [
                    'searchToolbar' => Template::createSearchToolBar($listSearchArr2, false),
//                    'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
                ]),
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError(
                $e->getMessage()
            );
        }
    }

    /**
     * 变更计划流程总负责人
     *
     *
     * @return mixed
     *
     * create by zqk 20190114
     */
    public function alterHeadChargerAction()
    {
        if (!UserPower::checkUserPower('Bpm_Plan_AlterHeadCharger')){
            return $this->sendViewError('无变更总负责人权限');
        }
        $id = $this->request->getQuery('iBPPId','string');
        $obj = XHBpmPlan::findFirst([
                'conditions'=>'bDelete=0 AND iBPPId =:id:',
                'bind'=>array('id'=>$id)
        ]);
        if (empty($obj)) {
            return $this->sendViewError('该流程计划不存在');
        }
        $chargeId = $obj->iChargeId;
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::easyUI();
        Assets::importJs('js/myMain.js');
        Assets::datetimePicker();
        Assets::importJs('js/plan/alterHeadCharger.js');
        $this->view->pick('plan/alterHeadChargerForm');
        $this->view->setVar('iBPPId', $id);
        $this->view->setVar('iChargeId', $chargeId);
    }


    public function saveAlterHeadChargerAction()
    {
        if (!UserPower::checkUserPower('Bpm_Plan_AlterHeadCharger')){
            return $this->sendErrorResponse(500,'无变更总负责人权限');
        }
        $iBPPId = $this->request->getPost('iBPPId', 'int');
        $iChargeId = $this->request->getPost('iChargeId', 'int');
        $sRearks = $this->request->getPost('sRemarks', 'int');
        if (User::isAdmin()) {
            $useName = 'admin';
        } else {
            $useName = Main::getLoginUserInfo('userName');
        }
//        $bNotify = $this->request->getPost('bNotify', 'int');
        try {
            $this->db->begin();
            $obj = XHBpmPlan::findFirst([
                'conditions'=>'bDelete=0 AND iBPPId =:id:',
                'bind'=>array('id'=>$iBPPId)
            ]);
            if (empty($obj)) {
                $this->db->rollback();
                return $this->sendErrorResponse(500,'该流程计划不存在');
            }
            if ($iChargeId == $obj->iChargeId) {
                $this->db->rollback();
                return $this->sendErrorResponse(500,'负责人未变更');
            }
            if ($iChargeId == 0) {
                $this->db->rollback();
                return $this->sendErrorResponse(500,'负责人不能为空');
            }
            $sOldChargeInfo = Hrm::getStaffInfo([$obj->iChargeId]);
            $sOldChargeName = array_values($sOldChargeInfo);
            $obj->iChargeId = $iChargeId;
            $re = $obj->save();
            if (!$re) {
                $this->db->rollback();
                return $this->sendErrorResponse(500,'操作失败');
            }

            $log = new XHBpmChargerLog();
            $sChargerInfo = Hrm::getStaffInfo([$iChargeId]);
            $sChargeName = array_values($sChargerInfo);
            $log->iChargeId = $iChargeId;
            $log->iBPPId = $iBPPId;
            $log->sChargeName = $sChargeName[0]['staffName'];
            $log->sContent = $useName .'：将负责人由'.$sOldChargeName[0]['staffName'].'变更为'. $sChargeName[0]['staffName'];
            $log->sRemarks = $sRearks;
            $res = $log->save();
            if (!$res) {
                $this->db->rollback();
                return $this->sendErrorResponse(500,'操作失败');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('操作成功');
        } catch (\Exception $exception) {
            $this->db->rollback();
            return $this->sendErrorResponse(500,'操作失败', $exception->getMessage());
        }

    }

    /**
     * 根据Id获取变更负责人的相关日志
     *
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180929
     */
    public function getAlterChargerLogAction()
    {
        $id = $this->request->getPost('id', 'int', 0);
        $logs = XHBpmChargerLog::find([
            'columns' => 'iCreateUserId,sChargeName,sRemarks,tCreateDate,sContent',
            'conditions' => 'bDelete = 0 And iBPPId = ' . $id,
            'order' => 'tCreateDate desc'
        ])->toArray();
        return $this->sendJsonResponse($logs);
    }
}
